Test Failed
Push — master ( c9e201...343a18 )
by Vítězslav
08:06
created

FlexiBeeRO::recordExists()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 11
nc 4
nop 1
dl 0
loc 18
ccs 0
cts 11
cp 0
crap 42
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/**
3
 * FlexiPeeHP - Read Only Access to FlexiBee class.
4
 *
5
 * @author     Vítězslav Dvořák <[email protected]>
6
 * @copyright  (C) 2015-2017 Spoje.Net
7
 */
8
9
namespace FlexiPeeHP;
10
11
/**
12
 * Základní třída pro čtení z FlexiBee
13
 *
14
 * @url https://demo.flexibee.eu/devdoc/
15
 */
16
class FlexiBeeRO extends \Ease\Brick
17
{
18
    /**
19
     * Version of FlexiPeeHP library
20
     *
21
     * @var string
22
     */
23
    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 26
    public function __construct($init = null, $options = [])
329
    {
330 26
        $this->init = $init;
331
332 26
        parent::__construct();
333 26
        $this->setUp($options);
334 26
        $this->curlInit();
335 26
        if (!empty($init)) {
336 22
            $this->processInit($init);
337 22
        }
338 26
    }
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 49
    public function setUp($options = [])
347
    {
348 49
        $this->setupProperty($options, 'company', 'FLEXIBEE_COMPANY');
349 49
        $this->setupProperty($options, 'url', 'FLEXIBEE_URL');
350 49
        $this->setupProperty($options, 'user', 'FLEXIBEE_LOGIN');
351 49
        $this->setupProperty($options, 'password', 'FLEXIBEE_PASSWORD');
352 49
        if (isset($options['evidence'])) {
353 44
            $this->setEvidence($options['evidence']);
354 44
        }
355 49
        $this->setupProperty($options, 'defaultUrlParams');
356 49
        if (isset($options['prefix'])) {
357 44
            $this->setPrefix($options['prefix']);
358 44
        }
359 49
        $this->setupProperty($options, 'debug');
360 49
        $this->updateApiURL();
361 49
    }
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 26
    public function setupProperty($options, $name, $constant = null)
371
    {
372 26
        if (isset($options[$name])) {
373 22
            $this->$name = $options[$name];
374 22
        } else {
375 26
            if (is_null($this->$name) && !empty($constant) && defined($constant)) {
376 26
                $this->$name = constant($constant);
377 26
            }
378
        }
379 26
    }
380
381
    /**
382
     * Inicializace CURL
383
     */
384 72
    public function curlInit()
385
    {
386 72
        $this->curl = \curl_init(); // create curl resource
387 72
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); // return content as a string from curl_exec
388 72
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true); // follow redirects (compatibility for future changes in FlexiBee)
389 72
        curl_setopt($this->curl, CURLOPT_HTTPAUTH, true);       // HTTP authentication
390 72
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); // FlexiBee by default uses Self-Signed certificates
391 72
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
392 72
        curl_setopt($this->curl, CURLOPT_VERBOSE, ($this->debug === true)); // For debugging
393 72
        curl_setopt($this->curl, CURLOPT_USERPWD,
394 72
            $this->user.':'.$this->password); // set username and password
395 72
    }
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 22
            $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 44
    public function setPrefix($prefix)
428
    {
429
        switch ($prefix) {
430 44
            case 'a': //Access
431 44
            case 'c': //Company
432 44
            case 'u': //User
433 44
            case 'g': //License Groups
434 44
            case 'admin':
435 44
            case 'status':
436 44
            case 'login-logout':
437 44
                $this->prefix = '/'.$prefix.'/';
438 44
                break;
439 22
            case null:
440 22
            case '':
441 22
            case '/':
442 22
                $this->prefix = '';
443 22
                break;
444 22
            default:
445 22
                throw new \Exception(sprintf('Unknown prefix %s', $prefix));
446 22
        }
447 44
    }
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 22
    public function setFormat($format)
457
    {
458 22
        $result = true;
459 22
        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 22
        if ($result === true) {
466 22
            $this->format = $format;
467 22
            $this->updateApiURL();
468 22
        }
469 22
        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 44
    public function setEvidence($evidence)
480
    {
481 44
        switch ($this->prefix) {
482 44
            case '/c/':
483 43
                if (array_key_exists($evidence, EvidenceList::$name)) {
484 41
                    $this->evidence = $evidence;
485 41
                    $result         = true;
486 41
                } else {
487 22
                    throw new \Exception(sprintf('Try to set unsupported evidence %s',
488 22
                        $evidence));
489
                }
490 41
                break;
491 3
            default:
492 3
                $this->evidence = $evidence;
493 3
                $result         = true;
494 3
                break;
495 44
        }
496 44
        $this->updateApiURL();
497 44
        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 49
    public function getEvidence()
507
    {
508 49
        return $this->evidence;
509
    }
510
511
    /**
512
     * Set used company.
513
     * Nastaví Firmu.
514
     *
515
     * @param string $company
516
     */
517 22
    public function setCompany($company)
518
    {
519 22
        $this->company = $company;
520 22
    }
521
522
    /**
523
     * Obtain company now used
524
     * Vrací právě používanou firmu
525
     *
526
     * @return string
527
     */
528 22
    public function getCompany()
529
    {
530 22
        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 42
    public function getResponseEvidence()
539
    {
540 42
        switch ($this->evidence) {
541 42
            case 'c':
542
                $evidence = 'company';
543
                break;
544 42
            case 'evidence-list':
545 2
                $evidence = 'evidence';
546 2
                break;
547 40
            default:
548 40
                $evidence = $this->getEvidence();
549 40
                break;
550 42
        }
551 42
        return $evidence;
552
    }
553
554
    /**
555
     * Převede rekurzivně Objekt na pole.
556
     *
557
     * @param object|array $object
558
     *
559
     * @return array
560
     */
561 22
    public static function object2array($object)
562
    {
563 22
        $result = null;
564 22
        if (is_object($object)) {
565 22
            $objectData = get_object_vars($object);
566 22
            if (is_array($objectData) && count($objectData)) {
567 22
                $result = array_map('self::object2array', $objectData);
568 22
            }
569 22
        } else {
570 22
            if (is_array($object)) {
571 22
                foreach ($object as $item => $value) {
572 22
                    $result[$item] = self::object2array($value);
573 22
                }
574 22
            } else {
575 22
                $result = $object;
576
            }
577
        }
578
579 22
        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 22
    public static function objectToID($object)
590
    {
591 22
        $resultID = null;
592 22
        if (is_object($object)) {
593 22
            $resultID = $object->__toString();
594 22
        } else {
595 22
            if (is_array($object)) {
596 22
                foreach ($object as $item => $value) {
597 22
                    $resultID[$item] = self::objectToID($value);
598 22
                }
599 22
            } else { //String
600 22
                $resultID = $object;
601
            }
602
        }
603
604 22
        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 47
    public function getEvidenceURL()
615
    {
616 47
        $evidenceUrl = $this->url.$this->prefix.$this->company;
617 47
        $evidence    = $this->getEvidence();
618 47
        if (!empty($evidence)) {
619 45
            $evidenceUrl .= '/'.$evidence;
620 45
        }
621 47
        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 26
    public function updateApiURL()
648
    {
649 26
        $this->apiURL = $this->getEvidenceURL();
650 26
        $id           = $this->__toString();
651 26
        if (!empty($id)) {
652 13
            $this->apiURL .= '/'.urlencode($id);
653 13
        }
654 26
        $this->apiURL .= '.'.$this->format;
655 26
    }
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 42
    public function performRequest($urlSuffix = null, $method = 'GET',
666
                                   $format = null)
667
    {
668 42
        $this->rowCount = null;
669
670 42
        if (preg_match('/^http/', $urlSuffix)) {
671 22
            $url = $urlSuffix;
672 42
        } elseif ($urlSuffix[0] == '/') {
673
            $url = $this->url.$urlSuffix;
674
        } else {
675 20
            $url = $this->evidenceUrlWithSuffix($urlSuffix);
676
        }
677
678 42
        $responseCode = $this->doCurlRequest($url, $method, $format);
679
680 42
        return strlen($this->lastCurlResponse) ? $this->parseResponse($this->rawResponseToArray($this->lastCurlResponse,
681 42
                    $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 22
    public function rawResponseToArray($responseRaw, $format)
693
    {
694
        switch ($format) {
695 22
            case 'json':
696 22
                $responseDecoded = json_decode($responseRaw, true, 10);
697 22
                $decodeError     = json_last_error_msg();
698 22
                if ($decodeError == 'No error') {
699 22
                    if (array_key_exists($this->nameSpace, $responseDecoded)) {
700 21
                        $responseDecoded = $responseDecoded[$this->nameSpace];
701 21
                    }
702 22
                } else {
703
                    $this->addStatusMessage('JSON Decoder: '.$decodeError,
704
                        'error');
705
                    $this->addStatusMessage($responseRaw, 'debug');
706
                }
707 22
                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 22
        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 22
    public function parseResponse($responseDecoded, $responseCode)
728
    {
729 22
        $response = null;
730
        switch ($responseCode) {
731 22
            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 22
            case 200: //Success Read
740 13
                $response         = $this->lastResult = $this->unifyResponseFormat($responseDecoded);
741 13
                if (isset($responseDecoded['@rowCount'])) {
742
                    $this->rowCount = (int) $responseDecoded['@rowCount'];
743
                }
744 13
                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 22
        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 22
    public function doCurlRequest($url, $method, $format = null)
794
    {
795 22
        if (is_null($format)) {
796 22
            $format = $this->format;
797 22
        }
798 22
        curl_setopt($this->curl, CURLOPT_URL, $url);
799
// Nastavení samotné operace
800 22
        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 22
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
803
804 22
        $httpHeaders = $this->defaultHttpHeaders;
805
806 22
        $formats = Formats::bySuffix();
807
808 22
        if (!isset($httpHeaders['Accept'])) {
809 22
            $httpHeaders['Accept'] = $formats[$format]['content-type'];
810 22
        }
811 22
        if (!isset($httpHeaders['Content-Type'])) {
812 22
            $httpHeaders['Content-Type'] = $formats[$format]['content-type'];
813 22
        }
814 22
        $httpHeadersFinal = [];
815 22
        foreach ($httpHeaders as $key => $value) {
816 22
            if (($key == 'User-Agent') && ($value == 'FlexiPeeHP')) {
817 22
                $value .= ' v'.self::$libVersion;
818 22
            }
819 22
            $httpHeadersFinal[] = $key.': '.$value;
820 22
        }
821
822 22
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
823
824
// Proveď samotnou operaci
825 22
        $this->lastCurlResponse            = curl_exec($this->curl);
826 22
        $this->curlInfo                    = curl_getinfo($this->curl);
827 22
        $this->curlInfo['when']            = microtime();
828 22
        $this->curlInfo['request_headers'] = $httpHeadersFinal;
829 22
        $this->responseFormat              = Formats::contentTypeToSuffix($this->curlInfo['content_type']);
830 22
        $this->lastResponseCode            = $this->curlInfo['http_code'];
831 22
        $this->lastCurlError               = curl_error($this->curl);
832 22
        if (strlen($this->lastCurlError)) {
833
            $this->addStatusMessage(sprintf('Curl Error (HTTP %d): %s',
834
                    $this->lastResponseCode, $this->lastCurlError), 'error');
835
        }
836
837 22
        if ($this->debug === true) {
838
            $this->saveDebugFiles();
839
        }
840
841 22
        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 19
    public function setAction($action)
852
    {
853 19
        $result           = false;
854 19
        $actionsAvailable = $this->getActionsInfo();
855 19
        if (is_array($actionsAvailable) && array_key_exists($action,
856 19
                $actionsAvailable)) {
857 15
            $this->action = $action;
858 15
            $result       = true;
859 15
        }
860 19
        return $result;
861
    }
862
863
    /**
864
     * Convert XML to array.
865
     *
866
     * @param string $xml
867
     *
868
     * @return array
869
     */
870 22
    public static function xml2array($xml)
871
    {
872 22
        $arr = [];
873
874 22
        if (is_string($xml)) {
875 22
            $xml = simplexml_load_string($xml);
876 22
        }
877
878 22
        foreach ($xml->children() as $r) {
879 22
            if (count($r->children()) == 0) {
880 22
                $arr[$r->getName()] = strval($r);
881 22
            } else {
882 22
                $arr[$r->getName()][] = self::xml2array($r);
883
            }
884 22
        }
885
886 22
        return $arr;
887
    }
888
889
    /**
890
     * Odpojení od FlexiBee.
891
     */
892 22
    public function disconnect()
893
    {
894 22
        if (is_resource($this->curl)) {
895 22
            curl_close($this->curl);
896 22
        }
897 22
        $this->curl = null;
898 22
    }
899
900
    /**
901
     * Disconnect CURL befere pass away
902
     */
903 22
    public function __destruct()
904
    {
905 22
        $this->disconnect();
906 22
    }
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 22
    public function getFlexiRow($recordID)
916
    {
917 22
        $record   = null;
918 22
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
919 22
        if (isset($response[$this->evidence])) {
920
            $record = $response[$this->evidence][0];
921
        }
922
923 22
        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 44
    public function getFlexiData($suffix = null, $conditions = null)
949
    {
950 44
        $finalUrl  = '';
951
        $urlParams = $this->defaultUrlParams;
952 44
953 4
        if (!is_null($conditions)) {
954
            if (is_array($conditions)) {
955
                $this->extractUrlParams($conditions, $urlParams);
956
                $conditions = $this->flexiUrl($conditions);
957
            }
958 4
959
            if (strlen($conditions) && ($conditions[0] != '/')) {
960
                $conditions = rawurlencode('('.($conditions).')');
961 4
            }
962
        }
963 44
964 22
        if (strlen($suffix)) {
965 22
            if (preg_match('/^http/', $suffix) || ($suffix[0] == '/')) {
966 22
                $finalUrl = $suffix;
967 22
            }
968
        }
969 44
970
        $finalUrl .= $conditions;
971 22
972 22
        if (count($urlParams)) {
973
            if (strstr($finalUrl, '?')) {
974
                $finalUrl .= '&';
975 22
            } else {
976
                $finalUrl .= '?';
977 22
            }
978 22
            $finalUrl .= http_build_query($urlParams);
979
        }
980 22
981
        $transactions = $this->performRequest($finalUrl, 'GET');
982 22
983 22
        $responseEvidence = $this->getResponseEvidence();
984 22
        if (is_array($transactions) && array_key_exists($responseEvidence,
985 13
                $transactions)) {
986 13
            $result = $transactions[$responseEvidence];
987
            if ((count($result) == 1) && (count(current($result)) == 0 )) {
988
                $result = null; // Response is empty Array
989 13
            }
990 9
        } else {
991
            $result = $transactions;
992
        }
993 22
994
        return $result;
995
    }
996
997
    /**
998
     * Načte záznam z FlexiBee a uloží v sobě jeho data
999
     * Read FlexiBee record and store it inside od object
1000
     *
1001
     * @param int $id ID or conditions
1002
     *
1003
     * @return int počet načtených položek
1004 44
     */
1005
    public function loadFromFlexiBee($id = null)
1006 44
    {
1007 44
        $data = [];
1008 22
        if (is_null($id)) {
1009 22
            $id = $this->getMyKey();
1010 44
        }
1011
        if (is_array($id)) {
1012
            $id = '('.self::flexiUrl($id).')';
1013 44
        }
1014 44
        $flexidata    = $this->getFlexiData($this->getEvidenceUrl().'/'.$id);
1015 44
        $this->apiURL = $this->curlInfo['url'];
1016 22
        if (is_array($flexidata) && (count($flexidata) == 1)) {
1017 22
            $data = current($flexidata);
1018 44
        }
1019
        return $this->takeData($data);
1020
    }
1021
1022
    /**
1023
     * Převede data do Json formátu pro FlexiBee.
1024
     * Convert data to FlexiBee like Json format
1025
     *
1026
     * @param array $data
1027
     *
1028
     * @return string
1029 22
     */
1030
    public function jsonizeData($data)
1031
    {
1032 22
        $dataToJsonize = [
1033 22
            $this->nameSpace => [
1034 22
                '@version' => $this->protoVersion,
1035 22
                $this->evidence => $this->objectToID($data),
1036 22
            ],
1037
        ];
1038 22
1039 15 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...
1040 15
            $dataToJsonize[$this->nameSpace][$this->evidence.'@action'] = $this->action;
1041 15
            $this->action                                               = null;
1042
        }
1043 22
1044 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...
1045
            $dataToJsonize[$this->nameSpace][$this->evidence.'@filter'] = $this->filter;
1046
        }
1047 22
1048
        return json_encode($dataToJsonize);
1049
    }
1050
1051
    /**
1052
     * Test if given record ID exists in FlexiBee.
1053
     *
1054
     * @param string|int $identifer
1055 22
     */
1056
    public function idExists($identifer = null)
1057 22
    {
1058
        if (is_null($identifer)) {
1059
            $identifer = $this->getMyKey();
1060 22
        }
1061 22
        $flexiData = $this->getFlexiData(
1062 22
            'detail=custom:'.$this->getmyKeyColumn(),
1063
            [$this->getmyKeyColumn() => $identifer]);
1064
1065
        return $flexiData;
1066
    }
1067
1068
    /**
1069
     * Test if given record exists in FlexiBee.
1070
     *
1071
     * @param array $data
1072
     * @return boolean Record presence status
1073
     */
1074
    public function recordExists($data = [])
1075
    {
1076
1077
        if (empty($data)) {
1078
            $data = $this->getData();
1079
        }
1080
1081
        $res = $this->getColumnsFromFlexibee([$this->myKeyColumn],
1082
            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...
1083
1084
        if (!count($res) || (isset($res['success']) && ($res['success'] == 'false'))
1085
            || !count($res[0])) {
1086
            $found = false;
1087
        } else {
1088
            $found = true;
1089
        }
1090
        return $found;
1091
    }
1092
1093
    /**
1094
     * Vrací z FlexiBee sloupečky podle podmínek.
1095
     *
1096
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
1097
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
1098
     *                                     sloupečku
1099
     * @return array
1100
     */
1101
    public function getAllFromFlexibee($conditions = null, $indexBy = null)
1102
    {
1103
        if (is_int($conditions)) {
1104
            $conditions = [$this->getmyKeyColumn() => $conditions];
1105
        }
1106
1107
        $flexiData = $this->getFlexiData('', $conditions);
1108
1109
        if (!is_null($indexBy)) {
1110
            $flexiData = $this->reindexArrayBy($flexiData);
1111
        }
1112
1113
        return $flexiData;
1114
    }
1115
1116
    /**
1117
     * Vrací z FlexiBee sloupečky podle podmínek.
1118
     *
1119
     * @param string[] $columnsList seznam položek
1120
     * @param array    $conditions  pole podmínek nebo ID záznamu
1121
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
1122
     *
1123
     * @return array
1124 22
     */
1125
    public function getColumnsFromFlexibee($columnsList, $conditions = null,
1126
                                           $indexBy = null)
1127 22
    {
1128 22
        $detail = 'full';
1129 22
        switch (gettype($columnsList)) {
1130
            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...
1131 22
                $conditions = [$this->getmyKeyColumn() => $conditions];
1132 22
            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...
1133 22
                if (!is_null($indexBy) && !array_key_exists($indexBy,
1134 22
                        $columnsList)) {
1135 22
                    $columnsList[] = $indexBy;
1136 22
                }
1137 22
                $columns = implode(',', array_unique($columnsList));
1138 22
                $detail  = 'custom:'.$columns;
1139
            default:
1140 22
                switch ($columnsList) {
1141
                    case 'id':
1142
                        $detail = 'id';
1143 22
                        break;
1144
                    case 'summary':
1145
                        $detail = 'summary';
1146 22
                        break;
1147 22
                    default:
1148 22
                        break;
1149 22
                }
1150 22
                break;
1151
        }
1152 22
1153
        $flexiData = $this->getFlexiData('detail='.$detail, $conditions);
1154
1155
        if (!is_null($indexBy) && count($flexiData) && count(current($flexiData))) {
1156
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
1157
        }
1158
1159
        return $flexiData;
1160
    }
1161
1162
    /**
1163
     * Vrací kód záznamu.
1164
     * Obtain record CODE
1165
     *
1166
     * @param mixed $data
1167
     *
1168
     * @return string
1169 22
     */
1170
    public function getKod($data = null, $unique = true)
1171 22
    {
1172
        $kod = null;
1173 22
1174 22
        if (is_null($data)) {
1175 22
            $data = $this->getData();
1176
        }
1177 22
1178 22
        if (is_string($data)) {
1179 22
            $data = [$this->nameColumn => $data];
1180
        }
1181 22
1182 22
        if (isset($data['kod'])) {
1183 22
            $kod = $data['kod'];
1184 22
        } else {
1185 22
            if (isset($data[$this->nameColumn])) {
1186 22
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
1187 22
                    \Ease\Sand::rip($data[$this->nameColumn]));
1188 22
            } else {
1189 22
                if (isset($data[$this->myKeyColumn])) {
1190 22
                    $kod = \Ease\Sand::rip($data[$this->myKeyColumn]);
1191
                }
1192
            }
1193
        }
1194 22
1195 22
        if (!strlen($kod)) {
1196 22
            $kod = 'NOTSET';
1197
        }
1198 22
1199 22
        if (strlen($kod) > 18) {
1200 22
            $kodfinal = strtoupper(substr($kod, 0, 18));
1201 22
        } else {
1202
            $kodfinal = strtoupper($kod);
1203
        }
1204 22
1205 22
        if ($unique) {
1206 22
            $counter = 0;
1207 22
            if (count($this->codes)) {
1208 22
                foreach ($this->codes as $codesearch => $keystring) {
1209 22
                    if (strstr($codesearch, $kodfinal)) {
1210 22
                        ++$counter;
1211 22
                    }
1212 22
                }
1213 22
            }
1214 22
            if ($counter) {
1215 22
                $kodfinal = $kodfinal.$counter;
1216
            }
1217 22
1218 22
            $this->codes[$kodfinal] = $kod;
1219
        }
1220 22
1221
        return $kodfinal;
1222
    }
1223
1224
    /**
1225
     * Write Operation Result.
1226
     *
1227
     * @param array  $resultData
1228
     * @param string $url        URL
1229
     * @return boolean Log save success
1230 31
     */
1231
    public function logResult($resultData = null, $url = null)
1232 31
    {
1233 31
        $logResult = false;
1234 30
        if (isset($resultData['success']) && ($resultData['success'] == 'false')) {
1235 8
            if (isset($resultData['message'])) {
1236 8
                $this->addStatusMessage($resultData['message'], 'warning');
1237 30
            }
1238 30
            $this->addStatusMessage('Error '.$this->lastResponseCode.': '.urldecode($url),
1239 30
                'warning');
1240 30
            unset($url);
1241 31
        }
1242
        if (is_null($resultData)) {
1243
            $resultData = $this->lastResult;
1244 31
        }
1245 23
        if (isset($url)) {
1246 23
            $this->logger->addStatusMessage(urldecode($url));
1247
        }
1248 31
1249 22
        if (isset($resultData['results'])) {
1250 22
            if ($resultData['success'] == 'false') {
1251 22
                $status = 'error';
1252 22
            } else {
1253
                $status = 'success';
1254 22
            }
1255 22
            foreach ($resultData['results'] as $result) {
1256 22
                if (isset($result['request-id'])) {
1257 22
                    $rid = $result['request-id'];
1258 22
                } else {
1259
                    $rid = '';
1260 22
                }
1261 22
                if (isset($result['errors'])) {
1262 22
                    foreach ($result['errors'] as $error) {
1263 22
                        $message = $error['message'];
1264
                        if (isset($error['for'])) {
1265
                            $message .= ' for: '.$error['for'];
1266 22
                        }
1267
                        if (isset($error['value'])) {
1268
                            $message .= ' value:'.$error['value'];
1269 22
                        }
1270
                        if (isset($error['code'])) {
1271
                            $message .= ' code:'.$error['code'];
1272 22
                        }
1273 22
                        $this->addStatusMessage($rid.': '.$message, $status);
1274 22
                    }
1275 22
                }
1276 22
            }
1277 31
        }
1278
        return $logResult;
1279
    }
1280
1281
    /**
1282
     * Save RAW Curl Request & Response to files in Temp directory
1283
     */
1284
    public function saveDebugFiles()
1285
    {
1286
        $tmpdir   = sys_get_temp_dir();
1287
        $fname    = $this->evidence.'-'.$this->curlInfo['when'].'.'.$this->format;
1288
        $reqname  = $tmpdir.'/request-'.$fname;
1289
        $respname = $tmpdir.'/response-'.$fname;
1290
        file_put_contents($reqname, $this->postFields);
1291
        file_put_contents($respname, $this->lastCurlResponse);
1292
    }
1293
1294
    /**
1295
     * Připraví data pro odeslání do FlexiBee
1296
     *
1297
     * @param string $data
1298
     */
1299
    public function setPostFields($data)
1300
    {
1301
        $this->postFields = $data;
1302
    }
1303
1304
    /**
1305
     * Generuje fragment url pro filtrování.
1306
     *
1307
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
1308
     *
1309
     * @param array  $data
1310
     * @param string $joiner default and/or
1311
     * @param string $defop  default operator
1312
     *
1313
     * @return string
1314 22
     */
1315
    public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq')
1316 22
    {
1317
        $parts = [];
1318 22
1319 22
        foreach ($data as $column => $value) {
1320 22
            if (is_integer($data[$column]) || is_float($data[$column])) {
1321 22
                $parts[$column] = $column.' eq \''.$data[$column].'\'';
1322 22
            } elseif (is_bool($data[$column])) {
1323 22
                $parts[$column] = $data[$column] ? $column.' eq true' : $column.' eq false';
1324 22
            } elseif (is_null($data[$column])) {
1325 22
                $parts[$column] = $column." is null";
1326
            } else {
1327 22
                switch ($value) {
1328 22
                    case '!null':
1329 22
                        $parts[$column] = $column." is not null";
1330 22
                        break;
1331 22
                    case 'is empty':
1332
                    case 'is not empty':
1333
                        $parts[$column] = $column.' '.$value;
1334 22
                        break;
1335 22
                    default:
1336
                        if ($column == 'stitky') {
1337
                            $parts[$column] = $column."='".self::code($data[$column])."'";
1338 22
                        } else {
1339
                            $parts[$column] = $column." $defop '".$data[$column]."'";
1340 22
                        }
1341 22
                        break;
1342
                }
1343 22
            }
1344 22
        }
1345
        return implode(' '.$joiner.' ', $parts);
1346
    }
1347
1348
    /**
1349
     * Obtain record/object identificator code: or id:
1350
     * Vrací identifikátor objektu code: nebo id:
1351
     *
1352
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1353
     * @return string|int indentifikátor záznamu reprezentovaného objektem
1354 49
     */
1355
    public function getRecordID()
1356 49
    {
1357 49
        $myCode = $this->getDataValue('kod');
1358 32
        if ($myCode) {
1359 32
            $id = 'code:'.$myCode;
1360 49
        } else {
1361 49
            $id = $this->getDataValue('id');
1362 9
            if (($this->debug === true) && is_null($id)) {
1363 9
                $this->addToLog('Object Data does not contain code: or id: cannot match with statement!',
1364 9
                    'warning');
1365
            }
1366 49
        }
1367
        return is_numeric($id) ? intval($id) : strval($id);
1368
    }
1369
1370
    /**
1371
     * Obtain record/object identificator code: or id:
1372
     * Vrací identifikátor objektu code: nebo id:
1373
     *
1374
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1375
     * @return string indentifikátor záznamu reprezentovaného objektem
1376 49
     */
1377
    public function __toString()
1378 49
    {
1379
        return strval($this->getRecordID());
1380
    }
1381
1382
    /**
1383
     * Gives you FlexiPeeHP class name for Given Evidence
1384
     *
1385
     * @param string $evidence
1386
     * @return string Class name
1387 22
     */
1388
    public static function evidenceToClassName($evidence)
1389 22
    {
1390
        return str_replace(' ', '', ucwords(str_replace('-', ' ', $evidence)));
1391
    }
1392
1393
    /**
1394
     * Obtain ID of first record in evidence
1395
     *
1396
     * @return string|null id or null if no records
1397 22
     */
1398
    public function getFirstRecordID()
1399 22
    {
1400 22
        $firstID    = null;
1401 22
        $firstIdRaw = $this->getColumnsFromFlexibee(['id'],
1402
            ['limit' => 1, 'order' => 'id'], 'id');
1403
        if (count($firstIdRaw)) {
1404
            $firstID = (int) current($firstIdRaw)['id'];
1405
        }
1406
        return $firstID;
1407
    }
1408
1409
    /**
1410
     * Vrací hodnotu daného externího ID
1411
     *
1412
     * @param string $want Which ? If empty,you obtain the first one.
1413
     * @return string
1414 22
     */
1415
    public function getExternalID($want = null)
1416 22
    {
1417 22
        $extid = null;
1418 22
        $ids   = $this->getDataValue('external-ids');
1419
        if (is_null($want)) {
1420
            if (count($ids)) {
1421
                $extid = current($ids);
1422
            }
1423 22
        } else {
1424
            if (!is_null($ids) && is_array($ids)) {
1425
                foreach ($ids as $id) {
1426
                    if (strstr($id, 'ext:'.$want)) {
1427
                        $extid = str_replace('ext:'.$want.':', '', $id);
1428
                    }
1429
                }
1430
            }
1431 22
        }
1432
        return $extid;
1433
    }
1434
1435
    /**
1436
     * Obtain actual GlobalVersion
1437
     * Vrací aktuální globální verzi změn
1438
     *
1439
     * @link https://www.flexibee.eu/api/dokumentace/ref/changes-api#globalVersion Globální Verze
1440
     * @return type
1441 21
     */
1442
    public function getGlobalVersion()
1443 21
    {
1444 21
        $globalVersion = null;
1445 21
        if (!count($this->lastResult) || !isset($this->lastResult['@globalVersion'])) {
1446 21
            $this->getFlexiData(null,
1447
                ['add-global-version' => 'true', 'limit' => 1]);
1448
        }
1449
1450
        if (isset($this->lastResult['@globalVersion'])) {
1451
            $globalVersion = intval($this->lastResult['@globalVersion']);
1452
        }
1453
1454
        return $globalVersion;
1455
    }
1456
1457
    /**
1458
     * Obtain content type of last response
1459
     *
1460
     * @return string
1461 22
     */
1462
    public function getResponseFormat()
1463 22
    {
1464 22
        if (isset($this->curlInfo['content_type'])) {
1465 22
            $responseFormat = $this->curlInfo['content_type'];
1466
        } else {
1467
            $responseFormat = null;
1468 22
        }
1469
        return $responseFormat;
1470
    }
1471
1472
    /**
1473
     * Return the same response format for one and multiplete results
1474
     *
1475
     * @param array $responseBody
1476
     * @return array
1477 35
     */
1478
    public function unifyResponseFormat($responseBody)
1479 35
    {
1480 35
        if (!is_array($responseBody) || array_key_exists('message',
1481 22
                $responseBody)) { //Unifi response format
1482 22
            $response = $responseBody;
1483 35
        } else {
1484 35
            $evidence = $this->getResponseEvidence();
1485 35
            if (array_key_exists($evidence, $responseBody)) {
1486 35
                $response        = [];
1487 35
                $evidenceContent = $responseBody[$evidence];
1488 35
                if (array_key_exists(0, $evidenceContent)) {
1489 35
                    $response[$evidence] = $evidenceContent; //Multiplete Results
1490 22
                } else {
1491
                    $response[$evidence][0] = $evidenceContent; //One result
1492 35
                }
1493
            } else {
1494
                if (isset($responseBody['priloha'])) {
1495
                    $response = $responseBody['priloha'];
1496
                } else {
1497
                    $response = $responseBody;
1498
                }
1499
            }
1500 35
        }
1501
        return $response;
1502
    }
1503
1504
    /**
1505
     * Obtain structure for current (or given) evidence
1506
     *
1507
     * @param string $evidence
1508
     * @return array Evidence structure
1509 22
     */
1510 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...
1511 22
    {
1512 22
        $columnsInfo = null;
1513 22
        if (is_null($evidence)) {
1514 22
            $evidence = $this->getEvidence();
1515 22
        }
1516 22
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1517 21
        if (isset(\FlexiPeeHP\Properties::$$propsName)) {
1518 21
            $columnsInfo = Properties::$$propsName;
1519 22
        }
1520
        return $columnsInfo;
1521
    }
1522
1523
    /**
1524
     * Obtain actions for current (or given) evidence
1525
     *
1526
     * @param string $evidence
1527
     * @return array Evidence structure
1528 22
     */
1529 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...
1530 22
    {
1531 22
        $actionsInfo = null;
1532 22
        if (is_null($evidence)) {
1533 22
            $evidence = $this->getEvidence();
1534 22
        }
1535 22
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1536 21
        if (isset(\FlexiPeeHP\Actions::$$propsName)) {
1537 21
            $actionsInfo = Actions::$$propsName;
1538 22
        }
1539
        return $actionsInfo;
1540
    }
1541
1542
    /**
1543
     * Obtain relations for current (or given) evidence
1544
     *
1545
     * @param string $evidence
1546
     * @return array Evidence structure
1547 22
     */
1548
    public function getRelationsInfo($evidence = null)
1549 22
    {
1550 22
        $relationsInfo = null;
1551 22
        if (is_null($evidence)) {
1552 22
            $evidence = $this->getEvidence();
1553 22
        }
1554 22
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1555 19
        if (isset(\FlexiPeeHP\Relations::$$propsName)) {
1556 19
            $relationsInfo = Relations::$$propsName;
1557 22
        }
1558
        return $relationsInfo;
1559
    }
1560
1561
    /**
1562
     * Obtain info for current (or given) evidence
1563
     *
1564
     * @param string $evidence
1565
     * @return array Evidence info
1566 22
     */
1567 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...
1568 22
    {
1569 22
        $evidencesInfo = null;
1570 22
        if (is_null($evidence)) {
1571 22
            $evidence = $this->getEvidence();
1572 22
        }
1573 16
        if (isset(EvidenceList::$evidences[$evidence])) {
1574 16
            $evidencesInfo = EvidenceList::$evidences[$evidence];
1575 22
        }
1576
        return $evidencesInfo;
1577
    }
1578
1579
    /**
1580
     * Obtain name for current (or given) evidence path
1581
     *
1582
     * @param string $evidence Evidence Path
1583
     * @return array Evidence info
1584 22
     */
1585 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...
1586 22
    {
1587 22
        $evidenceName = null;
1588 22
        if (is_null($evidence)) {
1589 22
            $evidence = $this->getEvidence();
1590 22
        }
1591 16
        if (isset(EvidenceList::$name[$evidence])) {
1592 16
            $evidenceName = EvidenceList::$name[$evidence];
1593 22
        }
1594
        return $evidenceName;
1595
    }
1596
1597
    /**
1598
     * Perform given action (if availble) on current evidence/record
1599
     * @url https://demo.flexibee.eu/devdoc/actions
1600
     *
1601
     * @param string $action one of evidence actions
1602
     * @param string $method ext|int External method call operation in URL.
1603
     *                               Internal add the @action element to request body
1604 15
     */
1605
    public function performAction($action, $method = 'ext')
1606 15
    {
1607
        $actionsAvailble = $this->getActionsInfo();
1608 15
1609 15
        if (is_array($actionsAvailble) && array_key_exists($action,
1610 15
                $actionsAvailble)) {
1611 15
            switch ($actionsAvailble[$action]['actionMakesSense']) {
1612 15
                case 'ONLY_WITH_INSTANCE_AND_NOT_IN_EDIT':
1613
                case 'ONLY_WITH_INSTANCE': //Add instance
1614
                    $urlSuffix = '/'.$this->__toString().'/'.$action.'.'.$this->format;
1615
                    break;
1616 15
1617 15
                default:
1618 15
                    $urlSuffix = '/'.$action;
1619 15
                    break;
1620
            }
1621
1622 15
            switch ($method) {
1623
                case 'int':
1624
                    $this->setAction($action);
1625
                    $this->setPostFields($this->jsonizeData($this->getData()));
1626
                    $result = $this->performRequest(null, 'POST');
1627
                    break;
1628 15
1629 15
                default:
1630 15
                    $result = $this->performRequest($urlSuffix, 'GET');
1631 15
                    break;
1632 15
            }
1633
        } else {
1634
            throw new \Exception(sprintf(_('Unsupported action %s for evidence %s'),
1635
                $action, $this->getEvidence()));
1636
        }
1637 15
1638
        return $result;
1639
    }
1640
1641
    /**
1642
     * Save current object to file
1643
     *
1644
     * @param string $destfile path to file
1645 22
     */
1646
    public function saveResponseToFile($destfile)
1647 22
    {
1648
        if (strlen($this->lastCurlResponse)) {
1649
            $this->doCurlRequest($this->apiURL, 'GET', $this->format);
1650 22
        }
1651 22
        file_put_contents($destfile, $this->lastCurlResponse);
1652
    }
1653
1654
    /**
1655
     * Obtain established relations listing
1656
     *
1657
     * @return array Null or Relations
1658
     */
1659
    public function getVazby($id = null)
1660
    {
1661
        if (is_null($id)) {
1662
            $id = $this->getRecordID();
1663
        }
1664
        if (!empty($id)) {
1665
            $vazbyRaw = $this->getColumnsFromFlexibee(['vazby'],
1666
                ['relations' => 'vazby', 'id' => $id]);
1667
            $vazby    = $vazbyRaw[0]['vazby'];
1668
        } else {
1669
            throw new \Exception(_('ID requied to get record relations '));
1670
        }
1671
        return $vazby;
1672
    }
1673
1674
    /**
1675
     * Gives You URL for Current Record in FlexiBee web interface
1676
     *
1677
     * @return string url
1678
     */
1679
    public function getFlexiBeeURL()
1680
    {
1681
        $parsed_url = parse_url(str_replace('.'.$this->format, '', $this->apiURL));
1682
        $scheme     = isset($parsed_url['scheme']) ? $parsed_url['scheme'].'://'
1683
                : '';
1684
        $host       = isset($parsed_url['host']) ? $parsed_url['host'] : '';
1685
        $port       = isset($parsed_url['port']) ? ':'.$parsed_url['port'] : '';
1686
        $user       = isset($parsed_url['user']) ? $parsed_url['user'] : '';
1687
        $pass       = isset($parsed_url['pass']) ? ':'.$parsed_url['pass'] : '';
1688
        $pass       = ($user || $pass) ? "$pass@" : '';
1689
        $path       = isset($parsed_url['path']) ? $parsed_url['path'] : '';
1690
        return $scheme.$user.$pass.$host.$port.$path;
1691
    }
1692
1693
    /**
1694
     * Set Record Key
1695
     *
1696
     * @param int|string $myKeyValue
1697
     * @return boolean
1698
     */
1699
    public function setMyKey($myKeyValue)
1700
    {
1701
        $res = parent::setMyKey($myKeyValue);
1702
        $this->updateApiURL();
1703
        return $res;
1704
    }
1705
1706
    /**
1707
     * Set or get ignore not found pages flag
1708
     *
1709
     * @param boolean $ignore set flag to
1710
     *
1711
     * @return boolean get flag state
1712
     */
1713
    public function ignore404($ignore = null)
1714
    {
1715
        if (!is_null($ignore)) {
1716
            $this->ignoreNotFound = $ignore;
1717
        }
1718
        return $this->ignoreNotFound;
1719
    }
1720
1721
    /**
1722
     * Send Document by mail
1723
     *
1724
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
1725
     *
1726
     * @param string $to
1727
     * @param string $subject
1728
     * @param string $body Email Text
1729
     *
1730
     * @return int http response code
1731
     */
1732
    public function sendByMail($to, $subject, $body, $cc = null)
1733
    {
1734
        $this->setPostFields($body);
1735
        $result = $this->doCurlRequest(urlencode($this->getRecordID()).'/odeslani-dokladu?to='.$to.'&subject='.urlencode($subject).'&cc='.$cc
1736
            , 'PUT', 'xml');
1737
        return $result == 200;
1738
    }
1739
1740
    /**
1741
     * Send all unsent Invoices by mail
1742
     *
1743
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
1744
     * @return int http response code
1745
     */
1746
    public function sendUnsent()
1747
    {
1748
        return $this->doCurlRequest('automaticky-odeslat-neodeslane', 'PUT', 'xml');
1749
    }
1750
1751
    /**
1752
     * FlexiBee date to PHP DateTime
1753
     *
1754
     * @param string $flexidate
1755
     *
1756
     * @return \DateTime | false
1757
     */
1758
    public static function flexiDateToDateTime($flexidate)
1759
    {
1760
        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 1760 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...
1761
    }
1762
1763
    /**
1764
     * Získá dokument v daném formátu
1765
     * Obtain document in given format
1766
     *
1767
     * @param string $format  pdf/csv/xml/json/ ...
1768
     *
1769
     * @return string|null filename downloaded or none
1770
     */
1771
    public function getInFormat($format)
1772
    {
1773
        $response = null;
1774
        if ($this->setFormat($format)) {
1775
            if (($this->doCurlRequest(($format == 'html') ? $this->apiURL.'?inDesktopApp=true'
1776
                            : $this->apiURL, 'GET') == 200)) {
1777
                $response = $this->lastCurlResponse;
1778
            }
1779
        }
1780
        return $response;
1781
    }
1782
1783
    /**
1784
     * Uloží dokument v daném formátu do složky v systému souborů
1785
     * Save document in given format to directory in filesystem
1786
     *
1787
     * @param string $format  pdf/csv/xml/json/ ...
1788
     * @param string $destDir where to put file (prefix)
1789
     *
1790
     * @return string|null filename downloaded or none
1791
     */
1792
    public function downloadInFormat($format, $destDir = './')
1793
    {
1794
        $fileOnDisk = null;
1795
        if ($this->setFormat($format)) {
1796
            $downloadTo = $destDir.$this->getEvidence().'_'.$this->getMyKey().'.'.$format;
1797
            if (($this->doCurlRequest($this->apiURL, 'GET') == 200) && (file_put_contents($downloadTo,
1798
                    $this->lastCurlResponse) !== false)) {
1799
                $fileOnDisk = $downloadTo;
1800
            }
1801
        }
1802
        return $fileOnDisk;
1803
    }
1804
1805
    /**
1806
     * Compile and send Report about Error500 to FlexiBee developers
1807
     * If FlexiBee is running on localost try also include java backtrace
1808
     *
1809
     * @param array $errorResponse result of parseError();
1810
     */
1811
    public function error500Reporter($errorResponse)
1812
    {
1813
        $ur = str_replace('/c/'.$this->company, '',
1814
            str_replace($this->url, '', $this->curlInfo['url']));
1815
        if (!array_key_exists($ur, $this->reports)) {
1816
            $tmpdir   = sys_get_temp_dir();
1817
            $myTime   = $this->curlInfo['when'];
1818
            $curlname = $tmpdir.'/curl-'.$this->evidence.'-'.$myTime.'.json';
1819
            file_put_contents($curlname,
1820
                json_encode($this->curlInfo, JSON_PRETTY_PRINT));
1821
1822
            $report = new \Ease\Mailer($this->reportRecipient,
1823
                'Error report 500 - '.$ur);
1824
1825
            $d     = dir($tmpdir);
1826
            while (false !== ($entry = $d->read())) {
1827
                if (strstr($entry, $myTime)) {
1828
                    $ext  = pathinfo($tmpdir.'/'.$entry, PATHINFO_EXTENSION);
1829
                    $mime = Formats::suffixToContentType($ext);
1830
                    $report->addFile($tmpdir.'/'.$entry,
1831
                        empty($mime) ? 'text/plain' : $mime);
1832
                }
1833
            }
1834
            $d->close();
1835
1836
            if ((strstr($this->url, '://localhost') || strstr($this->url,
1837
                    '://127.')) && file_exists('/var/log/flexibee.log')) {
1838
1839
                $fl = fopen("/var/log/flexibee.log", "r");
1840
                if ($fl) {
1841
                    $tracelog = [];
1842
                    for ($x_pos = 0, $ln = 0, $output = array(); fseek($fl,
1843
                            $x_pos, SEEK_END) !== -1; $x_pos--) {
1844
                        $char = fgetc($fl);
1845
                        if ($char === "\n") {
1846
                            $tracelog[] = $output[$ln];
1847
                            if (strstr($output[$ln], $errorResponse['message'])) {
1848
                                break;
1849
                            }
1850
                            $ln++;
1851
                            continue;
1852
                        }
1853
                        $output[$ln] = $char.((array_key_exists($ln, $output)) ? $output[$ln]
1854
                                : '');
1855
                    }
1856
1857
                    $trace     = implode("\n", array_reverse($tracelog));
1858
                    $tracefile = $tmpdir.'/trace-'.$this->evidence.'-'.$myTime.'.log';
1859
                    file_put_contents($tracefile, $trace);
1860
                    $report->addItem("\n\n".$trace);
1861
                    fclose($fl);
1862
                }
1863
            } else {
1864
                $report->addItem($errorResponse['message']);
1865
            }
1866
1867
            $licenseInfo = $this->performRequest($this->url.'/default-license.json');
1868
1869
            $report->addItem("\n\n".json_encode($licenseInfo['license'],
1870
                    JSON_PRETTY_PRINT));
1871
1872
            if ($report->send()) {
1873
                $this->reports[$ur] = $myTime;
1874
            }
1875
        }
1876
    }
1877
1878
    /**
1879
     * Returns code:CODE
1880
     *
1881
     * @param string $code
1882
     *
1883
     * @return string
1884
     */
1885
    public static function code($code)
1886
    {
1887
        return str_replace('code:', '', $code);
1888
    }
1889
1890
}
1891