Test Failed
Push — master ( 68ff63...99a915 )
by Vítězslav
08:13
created

FlexiBeeRO::flexiDateTimeToDateTime()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
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
     * Where to get JSON files with evidence stricture etc.
20
     * @var string
21
     */
22
    public static $infoDir = __DIR__.'/../../static';
23
24
    /**
25
     * Version of FlexiPeeHP library
26
     *
27
     * @var string
28
     */
29
    public static $libVersion = '1.8.4.3';
30
31
    /**
32
     * Základní namespace pro komunikaci s FlexiBee.
33
     * Basic namespace for communication with FlexiBee
34
     *
35
     * @var string Jmený prostor datového bloku odpovědi
36
     */
37
    public $nameSpace = 'winstrom';
38
39
    /**
40
     * URL of object data in FlexiBee
41
     * @var string url
42
     */
43
    public $apiURL = null;
44
45
    /**
46
     * Datový blok v poli odpovědi.
47
     * Data block in response field.
48
     *
49
     * @var string
50
     */
51
    public $resultField = 'results';
52
53
    /**
54
     * Verze protokolu použitého pro komunikaci.
55
     * Communication protocol version used.
56
     *
57
     * @var string Verze použitého API
58
     */
59
    public $protoVersion = '1.0';
60
61
    /**
62
     * Evidence užitá objektem.
63
     * Evidence used by object
64
     *
65
     * @link https://demo.flexibee.eu/c/demo/evidence-list Přehled evidencí
66
     * @var string
67
     */
68
    public $evidence = null;
69
70
    /**
71
     * Výchozí formát pro komunikaci.
72
     * Default communication format.
73
     *
74
     * @link https://www.flexibee.eu/api/dokumentace/ref/format-types Přehled možných formátů
75
     *
76
     * @var string json|xml|...
77
     */
78
    public $format = 'json';
79
80
    /**
81
     * formát příchozí odpovědi
82
     * response format
83
     *
84
     * @link https://www.flexibee.eu/api/dokumentace/ref/format-types Přehled možných formátů
85
     *
86
     * @var string json|xml|...
87
     */
88
    public $responseFormat = 'json';
89
90
    /**
91
     * Curl Handle.
92
     *
93
     * @var resource
94
     */
95
    public $curl = null;
96
97
    /**
98
     * @link https://demo.flexibee.eu/devdoc/company-identifier Identifikátor firmy
99
     * @var string
100
     */
101
    public $company = null;
102
103
    /**
104
     * Server[:port]
105
     * @var string
106
     */
107
    public $url = null;
108
109
    /**
110
     * REST API Username
111
     * @var string
112
     */
113
    public $user = null;
114
115
    /**
116
     * REST API Password
117
     * @var string
118
     */
119
    public $password = null;
120
121
    /**
122
     * @var array Pole HTTP hlaviček odesílaných s každým požadavkem
123
     */
124
    public $defaultHttpHeaders = ['User-Agent' => 'FlexiPeeHP'];
125
126
    /**
127
     * Default additional request url parameters after question mark
128
     *
129
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls   Common params
130
     * @link https://www.flexibee.eu/api/dokumentace/ref/paging Paging params
131
     * @var array
132
     */
133
    public $defaultUrlParams = ['limit' => 0];
134
135
    /**
136
     * Identifikační řetězec.
137
     *
138
     * @var string
139
     */
140
    public $init = null;
141
142
    /**
143
     * Sloupeček s názvem.
144
     *
145
     * @var string
146
     */
147
    public $nameColumn = 'nazev';
148
149
    /**
150
     * Sloupeček obsahující datum vložení záznamu do shopu.
151
     *
152
     * @var string
153
     */
154
    public $myCreateColumn = 'false';
155
156
    /**
157
     * Slopecek obsahujici datum poslení modifikace záznamu do shopu.
158
     *
159
     * @var string
160
     */
161
    public $myLastModifiedColumn = 'lastUpdate';
162
163
    /**
164
     * Klíčový idendifikátor záznamu.
165
     *
166
     * @var string
167
     */
168
    public $fbKeyColumn = 'id';
169
170
    /**
171
     * Informace o posledním HTTP requestu.
172
     *
173
     * @var *
174
     */
175
    public $curlInfo;
176
177
    /**
178
     * Informace o poslední HTTP chybě.
179
     *
180
     * @var string
181
     */
182
    public $lastCurlError = null;
183
184
    /**
185
     * Used codes storage.
186
     *
187
     * @var array
188
     */
189
    public $codes = null;
190
191
    /**
192
     * Last Inserted ID.
193
     *
194
     * @var int
195
     */
196
    public $lastInsertedID = null;
197
198
    /**
199
     * Default Line Prefix.
200
     *
201
     * @var string
202
     */
203
    public $prefix = '/c/';
204
205
    /**
206
     * Raw Content of last curl response
207
     *
208
     * @var string
209
     */
210
    public $lastCurlResponse;
211
212
    /**
213
     * HTTP Response code of last request
214
     *
215
     * @var int
216
     */
217
    public $lastResponseCode = null;
218
219
    /**
220
     * Body data  for next curl POST operation
221
     *
222
     * @var string
223
     */
224
    protected $postFields = null;
225
226
    /**
227
     * Last operation result data or message(s)
228
     *
229
     * @var array
230
     */
231
    public $lastResult = null;
232
233
    /**
234
     * Number from  @rowCount in response
235
     * @var int
236
     */
237
    public $rowCount = null;
238
239
    /**
240
     * Number from  @globalVersion
241
     * @var int
242
     */
243
    public $globalVersion = null;
244
245
    /**
246
     * @link https://www.flexibee.eu/api/dokumentace/ref/zamykani-odemykani/
247
     * @var string filter query
248
     */
249
    public $filter;
250
251
    /**
252
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
253
     * @var string
254
     */
255
    protected $action;
256
257
    /**
258
     * Pole akcí které podporuje ta která evidence
259
     * @link https://demo.flexibee.eu/c/demo/faktura-vydana/actions.json Např. Akce faktury
260
     * @var array
261
     */
262
    public $actionsAvailable = null;
263
264
    /**
265
     * Parmetry pro URL
266
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Všechny podporované parametry
267
     * @var array
268
     */
269
    public $urlParams = [
270
        'idUcetniObdobi',
271
        'dry-run',
272
        'fail-on-warning',
273
        'report-name',
274
        'report-lang',
275
        'report-sign',
276
        'detail', //See: https://www.flexibee.eu/api/dokumentace/ref/detail-levels
277
        'mode',
278
        'limit',
279
        'start',
280
        'order',
281
        'sort',
282
        'add-row-count',
283
        'relations',
284
        'includes',
285
        'use-ext-id',
286
        'use-internal-id',
287
        'stitky-as-ids',
288
        'only-ext-ids',
289
        'no-ext-ids',
290
        'no-ids',
291
        'code-as-id',
292
        'no-http-errors',
293
        'export-settings',
294
        'as-gui',
295
        'code-in-response',
296
        'add-global-version',
297
        'encoding',
298
        'delimeter',
299
        'format',
300
        'auth',
301
        'skupina-stitku',
302
        'dir',
303
        'relations',
304
        'relations',
305
        'xpath', // See: https://www.flexibee.eu/api/dokumentace/ref/xpath/
306
        'dry-run', // See: https://www.flexibee.eu/api/dokumentace/ref/dry-run/
307
        'inDesktopApp' // Note: Undocumented function (html only)
308
    ];
309
310
    /**
311
     * Save 404 results to log ?
312
     * @var boolean
313
     */
314
    protected $ignoreNotFound = false;
315
316
    /**
317
     * Array of errors caused by last request
318
     * @var array
319
     */
320
    private $errors = [];
321
322
    /**
323
     * List of Error500 reports sent
324
     * @var array
325
     */
326
    private $reports = [];
327
328
    /**
329
     * Send Error500 Report to
330
     * @var string email address
331
     */
332
    public $reportRecipient = '[email protected]';
333
334
    /**
335
     * Class for read only interaction with FlexiBee.
336
     *
337
     * @param mixed $init default record id or initial data
338
     * @param array $options Connection settings override
339
     */
340 70
    public function __construct($init = null, $options = [])
341
    {
342 70
        $this->init = $init;
343
344 70
        parent::__construct();
345 70
        $this->setUp($options);
346 70
        $this->curlInit();
347 70
        if (!empty($init)) {
348 22
            $this->processInit($init);
349 22
        }
350 70
    }
351
352
    /**
353
     * SetUp Object to be ready for connect
354
     *
355
     * @param array $options Object Options (company,url,user,password,evidence,
356
     *                                       prefix,defaultUrlParams,debug)
357
     */
358 93
    public function setUp($options = [])
359
    {
360 93
        $this->setupProperty($options, 'company', 'FLEXIBEE_COMPANY');
361 93
        $this->setupProperty($options, 'url', 'FLEXIBEE_URL');
362 93
        $this->setupProperty($options, 'user', 'FLEXIBEE_LOGIN');
363 93
        $this->setupProperty($options, 'password', 'FLEXIBEE_PASSWORD');
364 93
        if (isset($options['evidence'])) {
365 45
            $this->setEvidence($options['evidence']);
366 45
        }
367 93
        $this->setupProperty($options, 'defaultUrlParams');
368 93
        if (isset($options['prefix'])) {
369 45
            $this->setPrefix($options['prefix']);
370 45
        }
371 93
        if (array_key_exists('detail', $options)) {
372
            $this->defaultUrlParams['detail'] = $options['detail'];
373
        }
374 93
        $this->setupProperty($options, 'debug');
375 93
        $this->updateApiURL();
376 93
    }
377
378
    /**
379
     * Set up one of properties
380
     *
381
     * @param array  $options  array of given properties
382
     * @param string $name     name of property to process
383
     * @param string $constant load default property value from constant
384
     */
385 70
    public function setupProperty($options, $name, $constant = null)
386
    {
387 70
        if (isset($options[$name])) {
388 22
            $this->$name = $options[$name];
389 22
        } else {
390 70
            if (property_exists($this, $name) && !empty($constant) && defined($constant)) {
391 70
                $this->$name = constant($constant);
392 70
            }
393
        }
394 70
    }
395
396
    /**
397
     * Inicializace CURL
398
     */
399 116
    public function curlInit()
400
    {
401 116
        $this->curl = \curl_init(); // create curl resource
402 116
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); // return content as a string from curl_exec
403 116
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true); // follow redirects (compatibility for future changes in FlexiBee)
404 116
        curl_setopt($this->curl, CURLOPT_HTTPAUTH, true);       // HTTP authentication
405 116
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); // FlexiBee by default uses Self-Signed certificates
406 116
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
407 116
        curl_setopt($this->curl, CURLOPT_VERBOSE, ($this->debug === true)); // For debugging
408 116
        curl_setopt($this->curl, CURLOPT_USERPWD,
409 116
            $this->user.':'.$this->password); // set username and password
410 116
    }
411
412
    /**
413
     * Zinicializuje objekt dle daných dat. Možné hodnoty:
414
     *
415
     *  * 234                              - interní číslo záznamu k načtení
416
     *  * code:LOPATA                      - kód záznamu
417
     *  * BAGR                             - kód záznamu k načtení
418
     *  * ['id'=>24,'nazev'=>'hoblík']     - pole hodnot k předvyplnění
419
     *  * 743.json?relations=adresa,vazby  - část url s parametry k načtení
420
     *
421
     * @param mixed $init číslo/"(code:)kód"/(část)URI záznamu k načtení | pole hodnot k předvyplnění
422
     */
423 34
    public function processInit($init)
424
    {
425 34
        if (is_integer($init)) {
426 32
            $this->loadFromFlexiBee($init);
427 34
        } elseif (is_array($init)) {
428 12
            $this->takeData($init);
429 12
        } elseif (preg_match('/\.(json|xml|csv)/', $init)) {
430 10
            $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...
431 10
                            : $init)));
432 9
        } else {
433 7
            $this->loadFromFlexiBee($init);
434
        }
435 34
    }
436
437
    /**
438
     * Set URL prefix
439
     *
440
     * @param string $prefix
441
     */
442 45
    public function setPrefix($prefix)
443
    {
444
        switch ($prefix) {
445 45
            case 'a': //Access
446 45
            case 'c': //Company
447 45
            case 'u': //User
448 45
            case 'g': //License Groups
449 45
            case 'admin':
450 45
            case 'status':
451 45
            case 'login-logout':
452 45
                $this->prefix = '/'.$prefix.'/';
453 45
                break;
454 23
            case null:
455 23
            case '':
456 23
            case '/':
457 23
                $this->prefix = '';
458 23
                break;
459 23
            default:
460 23
                throw new \Exception(sprintf('Unknown prefix %s', $prefix));
461 23
        }
462 45
    }
463
464
    /**
465
     * Set communication format.
466
     * One of html|xml|json|csv|dbf|xls|isdoc|isdocx|edi|pdf|pdf|vcf|ical
467
     *
468
     * @param string $format
469
     * @return boolen format is availble
470
     */
471 23
    public function setFormat($format)
472
    {
473 23
        $result = true;
474 23
        if (($this->debug === true) && !empty($this->evidence) && isset(Formats::$$this->evidence)) {
475
            if (array_key_exists($format, array_flip(Formats::$$this->evidence))
476
                === false) {
477
                $result = false;
478
            }
479
        }
480 23
        if ($result === true) {
481 23
            $this->format = $format;
482 23
            $this->updateApiURL();
483 23
        }
484 23
        return $result;
485
    }
486
487
    /**
488
     * Nastaví Evidenci pro Komunikaci.
489
     * Set evidence for communication
490
     *
491
     * @param string $evidence evidence pathName to use
492
     * @return boolean evidence switching status
493
     */
494 45
    public function setEvidence($evidence)
495
    {
496 45
        switch ($this->prefix) {
497 45
            case '/c/':
498 44
                if ($this->debug === true) {
499 23
                    if (array_key_exists($evidence, EvidenceList::$name)) {
500
                        $this->evidence = $evidence;
501
                        $result         = true;
502
                    } else {
503 23
                        throw new \Exception(sprintf('Try to set unsupported evidence %s',
504 23
                                $evidence));
505
                    }
506
                } else {
507 41
                    $this->evidence = $evidence;
508 41
                    $result         = true;
509
                }
510 41
                break;
511 4
            default:
512 4
                $this->evidence = $evidence;
513 4
                $result         = true;
514 4
                break;
515 45
        }
516 45
        $this->updateApiURL();
517 45
        return $result;
518
    }
519
520
    /**
521
     * Vrací právě používanou evidenci pro komunikaci
522
     * Obtain current used evidence
523
     *
524
     * @return string
525
     */
526 91
    public function getEvidence()
527
    {
528 91
        return $this->evidence;
529
    }
530
531
    /**
532
     * Set used company.
533
     * Nastaví Firmu.
534
     *
535
     * @param string $company
536
     */
537 23
    public function setCompany($company)
538
    {
539 23
        $this->company = $company;
540 23
    }
541
542
    /**
543
     * Obtain company now used
544
     * Vrací právě používanou firmu
545
     *
546
     * @return string
547
     */
548 23
    public function getCompany()
549
    {
550 23
        return $this->company;
551
    }
552
553
    /**
554
     * Vrací název evidence použité v odpovědích z FlexiBee
555
     *
556
     * @return string
557
     */
558 46
    public function getResponseEvidence()
559
    {
560 46
        switch ($this->evidence) {
561 46
            case 'c':
562
                $evidence = 'company';
563
                break;
564 46
            case 'evidence-list':
565 2
                $evidence = 'evidence';
566 2
                break;
567 44
            default:
568 44
                $evidence = $this->getEvidence();
569 44
                break;
570 46
        }
571 46
        return $evidence;
572
    }
573
574
    /**
575
     * Převede rekurzivně Objekt na pole.
576
     *
577
     * @param object|array $object
578
     *
579
     * @return array
580
     */
581 23
    public static function object2array($object)
582
    {
583 23
        $result = null;
584 23
        if (is_object($object)) {
585 23
            $objectData = get_object_vars($object);
586 23
            if (is_array($objectData) && count($objectData)) {
587 23
                $result = array_map('self::object2array', $objectData);
588 23
            }
589 23
        } else {
590 23
            if (is_array($object)) {
591 23
                foreach ($object as $item => $value) {
592 23
                    $result[$item] = self::object2array($value);
593 23
                }
594 23
            } else {
595 23
                $result = $object;
596
            }
597
        }
598
599 23
        return $result;
600
    }
601
602
    /**
603
     * Převede rekurzivně v poli všechny objekty na jejich identifikátory.
604
     *
605
     * @param object|array $object
606
     *
607
     * @return array
608
     */
609 23
    public static function objectToID($object)
610
    {
611 23
        $resultID = null;
612 23
        if (is_object($object)) {
613 23
            $resultID = $object->__toString();
614 23
        } else {
615 23
            if (is_array($object)) {
616 23
                foreach ($object as $item => $value) {
617 23
                    $resultID[$item] = self::objectToID($value);
618 23
                }
619 23
            } else { //String
620 22
                $resultID = $object;
621
            }
622
        }
623
624 23
        return $resultID;
625
    }
626
627
    /**
628
     * Return basic URL for used Evidence
629
     *
630
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
631
     *
632
     * @return string Evidence URL
633
     */
634 89
    public function getEvidenceURL()
635
    {
636 89
        $evidenceUrl = $this->url.$this->prefix.$this->company;
637 89
        $evidence    = $this->getEvidence();
638 89
        if (!empty($evidence)) {
639 83
            $evidenceUrl .= '/'.$evidence;
640 83
        }
641 89
        return $evidenceUrl;
642
    }
643
644
    /**
645
     * Add suffix to Evidence URL
646
     *
647
     * @param string $urlSuffix
648
     *
649
     * @return string
650
     */
651 23
    public function evidenceUrlWithSuffix($urlSuffix)
652
    {
653 23
        $evidenceUrl = $this->getEvidenceUrl();
654 23
        if (!empty($urlSuffix)) {
655 23
            if (($urlSuffix[0] != '/') && ($urlSuffix[0] != ';') && ($urlSuffix[0]
656 23
                != '?')) {
657 23
                $evidenceUrl .= '/';
658 23
            }
659 23
            $evidenceUrl .= $urlSuffix;
660 23
        }
661 23
        return $evidenceUrl;
662
    }
663
664
    /**
665
     * Update $this->apiURL
666
     */
667 70
    public function updateApiURL()
668
    {
669 70
        $this->apiURL = $this->getEvidenceURL();
670 70
        $id           = $this->__toString();
671 70
        if (!empty($id)) {
672 10
            $this->apiURL .= '/'.urlencode($id);
673 10
        }
674 70
        $this->apiURL .= '.'.$this->format;
675 70
    }
676
677
    /**
678
     * Add params to url
679
     *
680
     * @param string  $url      originall url
681
     * @param array   $params   value to add
682
     * @param boolean $override replace already existing values ?
683
     *
684
     * @return string url with parameters added
685
     */
686 23
    public function addUrlParams($url, $params, $override = false)
687
    {
688 23
        $urlParts = parse_url($url);
689 23
        $urlFinal = '';
690 23
        if (array_key_exists('scheme', $urlParts)) {
691 23
            $urlFinal .= $urlParts['scheme'].'://'.$urlParts['host'];
692 23
        }
693 23
        if (array_key_exists('path', $urlParts)) {
694 23
            $urlFinal .= $urlParts['path'];
695 23
        }
696 23
        if (array_key_exists('query', $urlParts)) {
697 23
            parse_str($urlParts['query'], $queryUrlParams);
698 23
            $urlParams = $override ? array_merge($params, $queryUrlParams) : array_merge($queryUrlParams,
699 23
                    $params);
700 23
        } else {
701
            $urlParams = $params;
702
        }
703 23
        if (!empty($urlParams) && is_array($urlParams)) {
704 23
            $urlFinal .= '?'.http_build_query($urlParams);
705 23
        } else {
706
            $urlFinal .= '?'.$urlParams;
707
        }
708 23
        return $urlFinal;
709
    }
710
711
    /**
712
     * Add Default Url params to given url if not overrided
713
     *
714
     * @param string $urlRaw
715
     *
716
     * @return string url with default params added
717
     */
718 23
    public function addDefaultUrlParams($urlRaw)
719
    {
720 23
        return $this->addUrlParams($urlRaw, $this->defaultUrlParams, false);
721
    }
722
723
    /**
724
     * Funkce, která provede I/O operaci a vyhodnotí výsledek.
725
     *
726
     * @param string $urlSuffix část URL za identifikátorem firmy.
727
     * @param string $method    HTTP/REST metoda
728
     * @param string $format    Requested format
729
     * @return array|boolean Výsledek operace
730
     */
731 48
    public function performRequest($urlSuffix = null, $method = 'GET',
732
                                   $format = null)
733
    {
734 48
        $this->rowCount = null;
735
736 48
        if (preg_match('/^http/', $urlSuffix)) {
737 22
            $url = $urlSuffix;
738 48
        } elseif (strlen($urlSuffix) && ($urlSuffix[0] == '/')) {
739 4
            $url = $this->url.$urlSuffix;
740 4
        } else {
741 23
            $url = $this->evidenceUrlWithSuffix($urlSuffix);
742
        }
743
744 48
        $responseCode = $this->doCurlRequest($url, $method, $format);
745
746 48
        return $this->parseResponse($this->rawResponseToArray($this->lastCurlResponse,
0 ignored issues
show
Bug introduced by
It seems like $this->rawResponseToArra... $this->responseFormat) targeting FlexiPeeHP\FlexiBeeRO::rawResponseToArray() can also be of type string; however, FlexiPeeHP\FlexiBeeRO::parseResponse() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
747 48
                    $this->responseFormat), $responseCode);
748
    }
749
750
    /**
751
     * Parse Raw FlexiBee response in several formats
752
     *
753
     * @param string $responseRaw raw response body
754
     * @param string $format      Raw Response format json|xml|etc
755
     *
756
     * @return array
757
     */
758 25
    public function rawResponseToArray($responseRaw, $format)
759
    {
760
        switch ($format) {
761 25
            case 'json':
762 25
                $responseDecoded = $this->rawJsonToArray($responseRaw);
763 25
                break;
764
            case 'xml':
765
                $responseDecoded = $this->rawXmlToArray($this->lastCurlResponse);
766
                break;
767
            case 'txt':
768
            default:
769
                $responseDecoded = $this->lastCurlResponse;
770
                break;
771
        }
772 25
        return $responseDecoded;
773
    }
774
775
    /**
776
     * Convert FlexiBee Response JSON to Array
777
     *
778
     * @param string $rawJson
779
     * 
780
     * @return array
781
     */
782 25
    public function rawJsonToArray($rawJson)
783
    {
784 25
        $responseDecoded = json_decode($rawJson, true, 10);
785 25
        $decodeError     = json_last_error_msg();
786 25
        if ($decodeError == 'No error') {
787 25
            if (array_key_exists($this->nameSpace, $responseDecoded)) {
788 21
                $responseDecoded = $responseDecoded[$this->nameSpace];
789 21
            }
790 25
        } else {
791
            $this->addStatusMessage('JSON Decoder: '.$decodeError, 'error');
792
            $this->addStatusMessage($rawJson, 'debug');
793
        }
794 25
        return $responseDecoded;
795
    }
796
797
    /**
798
     * Convert FlexiBee Response XML to Array
799
     *
800
     * @param string $rawXML
801
     *
802
     * @return array
803
     */
804
    public function rawXmlToArray($rawXML)
805
    {
806
        return self::xml2array($rawXML);
807
    }
808
809
    /**
810
     * Parse Response array
811
     *
812
     * @param array $responseDecoded
813
     * @param int $responseCode Request Response Code
814
     *
815
     * @return array main data part of response
816
     */
817 25
    public function parseResponse($responseDecoded, $responseCode)
818
    {
819 25
        $response = null;
820
        switch ($responseCode) {
821 25
            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...
822
                if (isset($responseDecoded[$this->resultField][0]['id'])) {
823
                    $this->lastInsertedID = $responseDecoded[$this->resultField][0]['id'];
824
                    $this->setMyKey($this->lastInsertedID);
825
                    $this->apiURL         = $this->getEvidenceURL().'/'.$this->lastInsertedID;
826
                } else {
827
                    $this->lastInsertedID = null;
828
                }
829 25
            case 200: //Success Read
830 13
                $response         = $this->lastResult = $this->unifyResponseFormat($responseDecoded);
831 13
                if (isset($responseDecoded['@rowCount'])) {
832
                    $this->rowCount = (int) $responseDecoded['@rowCount'];
833
                }
834 13
                if (isset($responseDecoded['@globalVersion'])) {
835
                    $this->globalVersion = (int) $responseDecoded['@globalVersion'];
836
                }
837 13
                break;
838
839 12
            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...
840
                if ($this->debug === true) {
841
                    $this->error500Reporter($responseDecoded);
842
                }
843 12
            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...
844 11
                if ($this->ignoreNotFound === true) {
845
                    break;
846
                }
847 12
            case 400: //Bad Request parameters
848 12
            default: //Something goes wrong
849 12
                $this->addStatusMessage($this->lastResponseCode.': '.$this->curlInfo['url'],
850 12
                    'warning');
851 12
                if (is_array($responseDecoded)) {
852 12
                    $this->parseError($responseDecoded);
853 12
                }
854 12
                $this->logResult($responseDecoded, $this->curlInfo['url']);
855 12
                break;
856
        }
857 25
        return $response;
858
    }
859
860
    /**
861
     * Parse error message response
862
     *
863
     * @param array $responseDecoded
864
     * @return int number of errors processed
865
     */
866 12
    public function parseError(array $responseDecoded)
867
    {
868 12
        if (array_key_exists('results', $responseDecoded)) {
869
            $this->errors = $responseDecoded['results'][0]['errors'];
870
        } else {
871 12
            if (array_key_exists('message', $responseDecoded)) {
872 11
                $this->errors = [['message' => $responseDecoded['message']]];
873 11
            }
874
        }
875 12
        return count($this->errors);
876
    }
877
878
    /**
879
     * Vykonej HTTP požadavek
880
     *
881
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
882
     * @param string $url    URL požadavku
883
     * @param string $method HTTP Method GET|POST|PUT|OPTIONS|DELETE
884
     * @param string $format požadovaný formát komunikace
885
     * @return int HTTP Response CODE
886
     */
887 25
    public function doCurlRequest($url, $method, $format = null)
888
    {
889 25
        if (is_null($format)) {
890 25
            $format = $this->format;
891 25
        }
892 25
        curl_setopt($this->curl, CURLOPT_URL, $url);
893
// Nastavení samotné operace
894 25
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
895
//Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411
896 25
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
897
898 25
        $httpHeaders = $this->defaultHttpHeaders;
899
900 25
        $formats = Formats::bySuffix();
901
902 25
        if (!isset($httpHeaders['Accept'])) {
903 25
            $httpHeaders['Accept'] = $formats[$format]['content-type'];
904 25
        }
905 25
        if (!isset($httpHeaders['Content-Type'])) {
906 25
            $httpHeaders['Content-Type'] = $formats[$format]['content-type'];
907 25
        }
908 25
        $httpHeadersFinal = [];
909 25
        foreach ($httpHeaders as $key => $value) {
910 25
            if (($key == 'User-Agent') && ($value == 'FlexiPeeHP')) {
911 25
                $value .= ' v'.self::$libVersion;
912 25
            }
913 25
            $httpHeadersFinal[] = $key.': '.$value;
914 25
        }
915
916 25
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
917
918
// Proveď samotnou operaci
919 25
        $this->lastCurlResponse            = curl_exec($this->curl);
920 25
        $this->curlInfo                    = curl_getinfo($this->curl);
921 25
        $this->curlInfo['when']            = microtime();
922 25
        $this->curlInfo['request_headers'] = $httpHeadersFinal;
923 25
        $this->responseFormat              = isset($this->curlInfo['content_type'])
924 25
                ? Formats::contentTypeToSuffix($this->curlInfo['content_type']) : 'txt';
925 25
        $this->lastResponseCode            = $this->curlInfo['http_code'];
926 25
        $this->lastCurlError               = curl_error($this->curl);
927 25
        if (strlen($this->lastCurlError)) {
928
            $this->addStatusMessage(sprintf('Curl Error (HTTP %d): %s',
929
                    $this->lastResponseCode, $this->lastCurlError), 'error');
930
        }
931
932 25
        if ($this->debug === true) {
933
            $this->saveDebugFiles();
934
        }
935
936 25
        return $this->lastResponseCode;
937
    }
938
939
    /**
940
     * Nastaví druh prováděné akce.
941
     *
942
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
943
     * @param string $action
944
     * @return boolean
945
     */
946 23
    public function setAction($action)
947
    {
948 23
        $result           = false;
949 23
        $actionsAvailable = $this->getActionsInfo();
950 23
        if (is_array($actionsAvailable) && array_key_exists($action,
951 23
                $actionsAvailable)) {
952 15
            $this->action = $action;
953 15
            $result       = true;
954 15
        }
955 23
        return $result;
956
    }
957
958
    /**
959
     * Convert XML to array.
960
     *
961
     * @param string $xml
962
     *
963
     * @return array
964
     */
965 23
    public static function xml2array($xml)
966
    {
967 23
        $arr = [];
968 23
        if (!empty($xml)) {
969 23
            if (is_string($xml)) {
970 23
                $xml = simplexml_load_string($xml);
971 23
            }
972
973 23
            foreach ($xml->children() as $r) {
974 23
                if (count($r->children()) == 0) {
975 23
                    $arr[$r->getName()] = strval($r);
976 23
                } else {
977 23
                    $arr[$r->getName()][] = self::xml2array($r);
978
                }
979 23
            }
980 23
        }
981 23
        return $arr;
982
    }
983
984
    /**
985
     * Odpojení od FlexiBee.
986
     */
987 23
    public function disconnect()
988
    {
989 23
        if (is_resource($this->curl)) {
990 23
            curl_close($this->curl);
991 23
        }
992 23
        $this->curl = null;
993 23
    }
994
995
    /**
996
     * Disconnect CURL befere pass away
997
     */
998 23
    public function __destruct()
999
    {
1000 23
        $this->disconnect();
1001 23
    }
1002
1003
    /**
1004
     * Načte řádek dat z FlexiBee.
1005
     *
1006
     * @param int $recordID id požadovaného záznamu
1007
     *
1008
     * @return array
1009
     */
1010 23
    public function getFlexiRow($recordID)
1011
    {
1012 23
        $record   = null;
1013 23
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
1014 23
        if (isset($response[$this->evidence])) {
1015
            $record = $response[$this->evidence][0];
1016
        }
1017
1018 23
        return $record;
1019
    }
1020
1021
    /**
1022
     * Oddělí z pole podmínek ty jenž patří za ? v URL požadavku
1023
     *
1024
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
1025
     * @param array $conditions pole podmínek   - rendrují se do ()
1026
     * @param array $urlParams  pole parametrů  - rendrují za ?
1027
     */
1028
    public function extractUrlParams(&$conditions, &$urlParams)
1029
    {
1030
        foreach ($this->urlParams as $urlParam) {
1031
            if (isset($conditions[$urlParam])) {
1032
                \Ease\Sand::divDataArray($conditions, $urlParams, $urlParam);
1033
            }
1034
        }
1035
    }
1036
1037
    /**
1038
     * convert unicode to entities
1039
     *
1040
     * @param string $urlRaw
1041
     * @return string
1042
     */
1043
    public static function urlEncode($urlRaw)
1044
    {
1045
        return str_replace(['%27'], ["'"], rawurlencode($urlRaw));
1046
    }
1047
1048
    /**
1049
     * Načte data z FlexiBee.
1050
     *
1051
     * @param string $suffix     dotaz
1052
     * @param string|array $conditions Volitelný filtrovací výraz
1053
     *
1054
     * @return array Data obtained
1055
     */
1056 38
    public function getFlexiData($suffix = null, $conditions = null)
1057
    {
1058 38
        $finalUrl  = '';
1059 38
        $urlParams = $this->defaultUrlParams;
1060
1061 38
        if (!empty($conditions)) {
1062 9
            if (is_array($conditions)) {
1063 8
                $this->extractUrlParams($conditions, $urlParams);
1064 8
                $conditions = $this->flexiUrl($conditions);
1065 8
            }
1066
1067 9
            if (strlen($conditions) && ($conditions[0] != '/')) {
1068 1
                $conditions = '('.self::urlEncode($conditions).')';
1069 1
            }
1070 9
        }
1071
1072 38
        if (strlen($suffix)) {
1073 26
            if (preg_match('/^http/', $suffix) || ($suffix[0] == '/') || is_numeric($suffix)) {
1074 26
                $finalUrl = $suffix;
1075 26
            } else {
1076
                if (preg_match('/^(code|ext):(.*)/', $suffix, $matches)) {
1077
                    $finalUrl = $matches[1].':'.rawurlencode($matches[2]);
1078
                }
1079
            }
1080 26
        }
1081
1082 38
        $finalUrl .= $conditions;
1083
1084 38
        if (count($urlParams)) {
1085 38
            if (strstr($finalUrl, '?')) {
1086
                $finalUrl .= '&';
1087
            } else {
1088 38
                $finalUrl .= '?';
1089
            }
1090 38
            $finalUrl .= http_build_query($urlParams, null, '&',
1091 38
                PHP_QUERY_RFC3986);
1092 38
        }
1093
1094 38
        $transactions = $this->performRequest($finalUrl, 'GET');
1095
1096 38
        $responseEvidence = $this->getResponseEvidence();
1097 38
        if (is_array($transactions) && array_key_exists($responseEvidence,
1098 38
                $transactions)) {
1099 20
            $result = $transactions[$responseEvidence];
1100 20
            if ((count($result) == 1) && (count(current($result)) == 0 )) {
1101 7
                $result = null; // Response is empty Array
1102 7
            }
1103 20
        } else {
1104 18
            $result = $transactions;
1105
        }
1106
1107 38
        return $result;
1108
    }
1109
1110
    /**
1111
     * Načte záznam z FlexiBee a uloží v sobě jeho data
1112
     * Read FlexiBee record and store it inside od object
1113
     *
1114
     * @param int $id ID or conditions
1115
     *
1116
     * @return int počet načtených položek
1117
     */
1118 45
    public function loadFromFlexiBee($id = null)
1119
    {
1120 45
        $data = [];
1121 45
        if (is_null($id)) {
1122 23
            $id = $this->getMyKey();
1123 23
        }
1124 45
        if (is_array($id)) {
1125
            $id = rawurlencode('('.self::flexiUrl($id).')');
1126
        }
1127
1128 45
        if (preg_match('/^code/', $id)) {
1129
            $id = self::code(rawurlencode(self::uncode($id)));
1130
        }
1131
1132 45
        $flexidata    = $this->getFlexiData($this->getEvidenceUrl().'/'.$id);
1133 45
        $this->apiURL = $this->curlInfo['url'];
1134 45
        if (is_array($flexidata) && (count($flexidata) == 1)) {
1135 15
            $data = current($flexidata);
1136 15
        }
1137 45
        return $this->takeData($data);
1138
    }
1139
1140
    /**
1141
     * Převede data do Json formátu pro FlexiBee.
1142
     * Convert data to FlexiBee like Json format
1143
     *
1144
     * @param array $data
1145
     *
1146
     * @return string
1147
     */
1148 23
    public function jsonizeData($data)
1149
    {
1150
        $dataToJsonize = [
1151 23
            $this->nameSpace => [
1152 23
                '@version' => $this->protoVersion,
1153 23
                $this->evidence => $this->objectToID($data),
1154 23
            ],
1155 23
        ];
1156
1157 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...
1158 15
            $dataToJsonize[$this->nameSpace][$this->evidence.'@action'] = $this->action;
1159 15
            $this->action                                               = null;
1160 15
        }
1161
1162 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...
1163
            $dataToJsonize[$this->nameSpace][$this->evidence.'@filter'] = $this->filter;
1164
        }
1165
1166 23
        return json_encode($dataToJsonize);
1167
    }
1168
1169
    /**
1170
     * Test if given record ID exists in FlexiBee.
1171
     *
1172
     * @param boolean $identifer presence state
1173
     */
1174 15
    public function idExists($identifer = null)
1175
    {
1176 15
        if (is_null($identifer)) {
1177 8
            $identifer = $this->getMyKey();
1178 8
        }
1179 15
        $ignorestate = $this->ignore404();
1180 15
        $this->ignore404(true);
1181 15
        $this->getFlexiData(null,
1182
            [
1183 15
                'detail' => 'custom:'.$this->getmyKeyColumn(),
1184 15
                $this->getmyKeyColumn() => $identifer
1185 15
        ]);
1186 15
        $this->ignore404($ignorestate);
1187 15
        return $this->lastResponseCode == 200;
1188
    }
1189
1190
    /**
1191
     * Test if given record exists in FlexiBee.
1192
     *
1193
     * @param array $data
1194
     * @return boolean Record presence status
1195
     */
1196 21
    public function recordExists($data = [])
1197
    {
1198
1199 21
        if (empty($data)) {
1200 16
            $data = $this->getData();
1201 16
        }
1202 21
        $ignorestate = $this->ignore404();
1203 21
        $this->ignore404(true);
1204 21
        $res         = $this->getColumnsFromFlexibee([$this->myKeyColumn],
1205 21
            [self::flexiUrl($data)]);
1206
1207 21
        if (!count($res) || (isset($res['success']) && ($res['success'] == 'false'))
1208 21
            || !count($res[0])) {
1209 21
            $found = false;
1210 21
        } else {
1211 9
            $found = true;
1212
        }
1213 21
        $this->ignore404($ignorestate);
1214 21
        return $found;
1215
    }
1216
1217
    /**
1218
     * Vrací z FlexiBee sloupečky podle podmínek.
1219
     *
1220
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
1221
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
1222
     *                                     sloupečku
1223
     * @return array
1224
     */
1225
    public function getAllFromFlexibee($conditions = null, $indexBy = null)
1226
    {
1227
        if (is_int($conditions)) {
1228
            $conditions = [$this->getmyKeyColumn() => $conditions];
1229
        }
1230
1231
        $flexiData = $this->getFlexiData('', $conditions);
1232
1233
        if (!is_null($indexBy)) {
1234
            $flexiData = $this->reindexArrayBy($flexiData);
1235
        }
1236
1237
        return $flexiData;
1238
    }
1239
1240
    /**
1241
     * Vrací z FlexiBee sloupečky podle podmínek.
1242
     *
1243
     * @param string[] $columnsList seznam položek
1244
     * @param array    $conditions  pole podmínek nebo ID záznamu
1245
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
1246
     *
1247
     * @return array
1248
     */
1249 23
    public function getColumnsFromFlexibee($columnsList, $conditions = [],
1250
                                           $indexBy = null)
1251
    {
1252 23
        $detail = 'full';
1253 23
        switch (gettype($columnsList)) {
1254 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...
1255
                $conditions = [$this->getmyKeyColumn() => $conditions];
1256 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...
1257 23
                if (!is_null($indexBy) && !array_key_exists($indexBy,
1258 23
                        $columnsList)) {
1259 23
                    $columnsList[] = $indexBy;
1260 23
                }
1261 23
                $columns = implode(',', array_unique($columnsList));
1262 23
                $detail  = 'custom:'.$columns;
1263 23
            default:
1264
                switch ($columnsList) {
1265 23
                    case 'id':
1266
                        $detail = 'id';
1267
                        break;
1268 23
                    case 'summary':
1269
                        $detail = 'summary';
1270
                        break;
1271 23
                    default:
1272 23
                        break;
1273 23
                }
1274 23
                break;
1275 23
        }
1276
1277 23
        $conditions['detail'] = $detail;
1278
1279 23
        $flexiData = $this->getFlexiData(null, $conditions);
1280
1281 23
        if (!is_null($indexBy) && count($flexiData) && count(current($flexiData))) {
1282 12
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
1283 10
        }
1284
1285 21
        return $flexiData;
1286
    }
1287
1288
    /**
1289
     * Vrací kód záznamu.
1290
     * Obtain record CODE
1291
     *
1292
     * @param mixed $data
1293
     *
1294
     * @return string
1295
     */
1296 23
    public function getKod($data = null, $unique = true)
1297
    {
1298 23
        $kod = null;
1299
1300 23
        if (is_null($data)) {
1301 23
            $data = $this->getData();
1302 23
        }
1303
1304 23
        if (is_string($data)) {
1305 23
            $data = [$this->nameColumn => $data];
1306 23
        }
1307
1308 23
        if (isset($data['kod'])) {
1309 23
            $kod = $data['kod'];
1310 23
        } else {
1311 23
            if (isset($data[$this->nameColumn])) {
1312 23
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
1313 23
                    \Ease\Sand::rip($data[$this->nameColumn]));
1314 23
            } else {
1315 23
                if (isset($data[$this->myKeyColumn])) {
1316 23
                    $kod = \Ease\Sand::rip($data[$this->myKeyColumn]);
1317 23
                }
1318
            }
1319
        }
1320
1321 23
        if (!strlen($kod)) {
1322 23
            $kod = 'NOTSET';
1323 23
        }
1324
1325 23
        if (strlen($kod) > 18) {
1326 23
            $kodfinal = strtoupper(substr($kod, 0, 18));
1327 23
        } else {
1328 23
            $kodfinal = strtoupper($kod);
1329
        }
1330
1331 23
        if ($unique) {
1332 23
            $counter = 0;
1333 23
            if (count($this->codes)) {
1334 23
                foreach ($this->codes as $codesearch => $keystring) {
1335 23
                    if (strstr($codesearch, $kodfinal)) {
1336 23
                        ++$counter;
1337 23
                    }
1338 23
                }
1339 23
            }
1340 23
            if ($counter) {
1341 23
                $kodfinal = $kodfinal.$counter;
1342 23
            }
1343
1344 23
            $this->codes[$kodfinal] = $kod;
1345 23
        }
1346
1347 23
        return self::code($kodfinal);
1348
    }
1349
1350
    /**
1351
     * Write Operation Result.
1352
     *
1353
     * @param array  $resultData
1354
     * @param string $url        URL
1355
     * @return boolean Log save success
1356
     */
1357 35
    public function logResult($resultData = null, $url = null)
1358
    {
1359 35
        $logResult = false;
1360 35
        if (isset($resultData['success']) && ($resultData['success'] == 'false')) {
1361 34
            if (isset($resultData['message'])) {
1362 11
                $this->addStatusMessage($resultData['message'], 'warning');
1363 11
            }
1364 34
            $this->addStatusMessage('Error '.$this->lastResponseCode.': '.urldecode($url),
1365 34
                'warning');
1366 34
            unset($url);
1367 34
        }
1368 35
        if (is_null($resultData)) {
1369
            $resultData = $this->lastResult;
1370
        }
1371 35
        if (isset($url)) {
1372 24
            $this->logger->addStatusMessage($this->lastResponseCode.':'.urldecode($url));
1373 24
        }
1374
1375 35
        if (isset($resultData['results'])) {
1376 23
            if ($resultData['success'] == 'false') {
1377 23
                $status = 'error';
1378 23
            } else {
1379 23
                $status = 'success';
1380
            }
1381 23
            foreach ($resultData['results'] as $result) {
1382 23
                if (isset($result['request-id'])) {
1383 23
                    $rid = $result['request-id'];
1384 23
                } else {
1385 23
                    $rid = '';
1386
                }
1387 23
                if (isset($result['errors'])) {
1388 23
                    foreach ($result['errors'] as $error) {
1389 23
                        $message = $error['message'];
1390 23
                        if (isset($error['for'])) {
1391
                            $message .= ' for: '.$error['for'];
1392
                        }
1393 23
                        if (isset($error['value'])) {
1394
                            $message .= ' value:'.$error['value'];
1395
                        }
1396 23
                        if (isset($error['code'])) {
1397
                            $message .= ' code:'.$error['code'];
1398
                        }
1399 23
                        $this->addStatusMessage($rid.': '.$message, $status);
1400 23
                    }
1401 23
                }
1402 23
            }
1403 23
        }
1404 35
        return $logResult;
1405
    }
1406
1407
    /**
1408
     * Save RAW Curl Request & Response to files in Temp directory
1409
     */
1410
    public function saveDebugFiles()
1411
    {
1412
        $tmpdir   = sys_get_temp_dir();
1413
        $fname    = $this->evidence.'-'.$this->curlInfo['when'].'.'.$this->format;
1414
        $reqname  = $tmpdir.'/request-'.$fname;
1415
        $respname = $tmpdir.'/response-'.$fname;
1416
        file_put_contents($reqname, $this->postFields);
1417
        file_put_contents($respname, $this->lastCurlResponse);
1418
    }
1419
1420
    /**
1421
     * Připraví data pro odeslání do FlexiBee
1422
     *
1423
     * @param string $data
1424
     */
1425
    public function setPostFields($data)
1426
    {
1427
        $this->postFields = $data;
1428
    }
1429
1430
    /**
1431
     * Generuje fragment url pro filtrování.
1432
     *
1433
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
1434
     *
1435
     * @param array  $data
1436
     * @param string $joiner default and/or
1437
     * @param string $defop  default operator
1438
     *
1439
     * @return string
1440
     */
1441 23
    public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq')
1442
    {
1443 23
        $parts = [];
1444
1445 23
        foreach ($data as $column => $value) {
1446 23
            if (!is_numeric($column)) {
1447 23
                if (is_integer($data[$column]) || is_float($data[$column])) {
1448 23
                    $parts[$column] = $column.' eq \''.$data[$column].'\'';
1449 23
                } elseif (is_bool($data[$column])) {
1450 23
                    $parts[$column] = $data[$column] ? $column.' eq true' : $column.' eq false';
1451 23
                } elseif (is_null($data[$column])) {
1452 23
                    $parts[$column] = $column." is null";
1453 23
                } else {
1454
                    switch ($value) {
1455 23
                        case '!null':
1456 23
                            $parts[$column] = $column." is not null";
1457 23
                            break;
1458 23
                        case 'is empty':
1459 23
                        case 'is not empty':
1460
                            $parts[$column] = $column.' '.$value;
1461
                            break;
1462 23
                        default:
1463 23
                            if ($column == 'stitky') {
1464
                                $parts[$column] = $column."='".self::code($data[$column])."'";
1465
                            } else {
1466 23
                                $parts[$column] = $column." $defop '".$data[$column]."'";
1467
                            }
1468 23
                            break;
1469 23
                    }
1470
                }
1471 23
            } else {
1472
                $parts[] = $value;
1473
            }
1474 23
        }
1475 23
        return implode(' '.$joiner.' ', $parts);
1476
    }
1477
1478
    /**
1479
     * Obtain record/object identificator code: or id:
1480
     * Vrací identifikátor objektu code: nebo id:
1481
     *
1482
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1483
     * @return string|int indentifikátor záznamu reprezentovaného objektem
1484
     */
1485 93
    public function getRecordID()
1486
    {
1487 93
        $myCode = $this->getDataValue('kod');
1488 93
        if ($myCode) {
1489 31
            $id = self::code($myCode);
1490 31
        } else {
1491 93
            $id = $this->getDataValue('id');
1492 93
            if (($this->debug === true) && is_null($id)) {
1493 12
                $this->addToLog('Object Data does not contain code: or id: cannot match with statement!',
1494 12
                    'warning');
1495 12
            }
1496
        }
1497 93
        return is_numeric($id) ? intval($id) : strval($id);
1498
    }
1499
1500
    /**
1501
     * Obtain record/object identificator code: or id:
1502
     * Vrací identifikátor objektu code: nebo id:
1503
     *
1504
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1505
     * @return string indentifikátor záznamu reprezentovaného objektem
1506
     */
1507 93
    public function __toString()
1508
    {
1509 93
        return strval($this->getRecordID());
1510
    }
1511
1512
    /**
1513
     * Gives you FlexiPeeHP class name for Given Evidence
1514
     *
1515
     * @param string $evidence
1516
     * @return string Class name
1517
     */
1518 23
    public static function evidenceToClassName($evidence)
1519
    {
1520 23
        return str_replace(' ', '', ucwords(str_replace('-', ' ', $evidence)));
1521
    }
1522
1523
    /**
1524
     * Obtain ID of first record in evidence
1525
     *
1526
     * @return string|null id or null if no records
1527
     */
1528 16
    public function getFirstRecordID()
1529
    {
1530 16
        $firstID    = null;
1531 16
        $firstIdRaw = $this->getColumnsFromFlexibee(['id'],
1532 16
            ['limit' => 1, 'order' => 'id'], 'id');
1533 14
        if (count($firstIdRaw)) {
1534 11
            $firstID = (int) current($firstIdRaw)['id'];
1535 11
        }
1536 14
        return $firstID;
1537
    }
1538
1539
    /**
1540
     * Vrací hodnotu daného externího ID
1541
     *
1542
     * @param string $want Which ? If empty,you obtain the first one.
1543
     * @return string
1544
     */
1545 23
    public function getExternalID($want = null)
1546
    {
1547 23
        $extid = null;
1548 23
        $ids   = $this->getDataValue('external-ids');
1549 23
        if (is_null($want)) {
1550 23
            if (count($ids)) {
1551 23
                $extid = current($ids);
1552 23
            }
1553 23
        } else {
1554 23
            if (!is_null($ids) && is_array($ids)) {
1555 23
                foreach ($ids as $id) {
1556 23
                    if (strstr($id, 'ext:'.$want)) {
1557 23
                        $extid = str_replace('ext:'.$want.':', '', $id);
1558 23
                    }
1559 23
                }
1560 23
            }
1561
        }
1562 23
        return $extid;
1563
    }
1564
1565
    /**
1566
     * Obtain actual GlobalVersion
1567
     * Vrací aktuální globální verzi změn
1568
     *
1569
     * @link https://www.flexibee.eu/api/dokumentace/ref/changes-api#globalVersion Globální Verze
1570
     * @return type
1571
     */
1572 22
    public function getGlobalVersion()
1573
    {
1574 22
        $this->getFlexiData(null, ['add-global-version' => 'true', 'limit' => 1]);
1575
1576 22
        return $this->globalVersion;
1577
    }
1578
1579
    /**
1580
     * Obtain content type of last response
1581
     *
1582
     * @return string
1583
     */
1584 23
    public function getResponseFormat()
1585
    {
1586 23
        if (isset($this->curlInfo['content_type'])) {
1587 22
            $responseFormat = $this->curlInfo['content_type'];
1588 22
        } else {
1589 1
            $responseFormat = null;
1590
        }
1591 23
        return $responseFormat;
1592
    }
1593
1594
    /**
1595
     * Return the same response format for one and multiplete results
1596
     *
1597
     * @param array $responseBody
1598
     * @return array
1599
     */
1600 32
    public function unifyResponseFormat($responseBody)
1601
    {
1602 32
        if (!is_array($responseBody) || array_key_exists('message',
1603 32
                $responseBody)) { //Unifi response format
1604 22
            $response = $responseBody;
1605 22
        } else {
1606 32
            $evidence = $this->getResponseEvidence();
1607 32
            if (array_key_exists($evidence, $responseBody)) {
1608 32
                $response        = [];
1609 32
                $evidenceContent = $responseBody[$evidence];
1610 32
                if (array_key_exists(0, $evidenceContent)) {
1611 32
                    $response[$evidence] = $evidenceContent; //Multiplete Results
1612 32
                } else {
1613 22
                    $response[$evidence][0] = $evidenceContent; //One result
1614
                }
1615 32
            } else {
1616
                if (isset($responseBody['priloha'])) {
1617
                    $response = $responseBody['priloha'];
1618
                } else {
1619
                    if (array_key_exists('results', $responseBody)) {
1620
                        $response = $responseBody['results'];
1621
                    } else {
1622
                        $response = $responseBody;
1623
                    }
1624
                }
1625
            }
1626
        }
1627 32
        return $response;
1628
    }
1629
1630
    /**
1631
     * Obtain structure for current (or given) evidence
1632
     *
1633
     * @param string $evidence
1634
     * @return array Evidence structure
1635
     */
1636 23
    public function getColumnsInfo($evidence = null)
1637
    {
1638 23
        $columnsInfo = null;
1639 23
        $infoSource  = self::$infoDir.'/Properties.'.(empty($evidence) ? $this->getEvidence()
1640 23
                : $evidence).'.json';
1641 23
        if (file_exists($infoSource)) {
1642 16
            $columnsInfo = json_decode(file_get_contents($infoSource), true);
1643 16
        }
1644 23
        return $columnsInfo;
1645
    }
1646
1647
    /**
1648
     * Obtain actions for current (or given) evidence
1649
     *
1650
     * @param string $evidence
1651
     * @return array Evidence structure
1652
     */
1653 23
    public function getActionsInfo($evidence = null)
1654
    {
1655 23
        $actionsInfo = null;
1656 23
        if (is_null($evidence)) {
1657 23
            $evidence = $this->getEvidence();
1658 23
        }
1659 23
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1660 23
        if (isset(\FlexiPeeHP\Actions::$$propsName)) {
1661 23
            $actionsInfo = Actions::$$propsName;
1662 23
        }
1663 23
        return $actionsInfo;
1664
    }
1665
1666
    /**
1667
     * Obtain relations for current (or given) evidence
1668
     *
1669
     * @param string $evidence
1670
     * @return array Evidence structure
1671
     */
1672 23
    public function getRelationsInfo($evidence = null)
1673
    {
1674 23
        $relationsInfo = null;
1675 23
        if (is_null($evidence)) {
1676 23
            $evidence = $this->getEvidence();
1677 23
        }
1678 23
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1679 23
        if (isset(\FlexiPeeHP\Relations::$$propsName)) {
1680 13
            $relationsInfo = Relations::$$propsName;
1681 13
        }
1682 23
        return $relationsInfo;
1683
    }
1684
1685
    /**
1686
     * Obtain info for current (or given) evidence
1687
     *
1688
     * @param string $evidence
1689
     * @return array Evidence info
1690
     */
1691 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...
1692
    {
1693 23
        $evidencesInfo = null;
1694 23
        if (is_null($evidence)) {
1695 23
            $evidence = $this->getEvidence();
1696 23
        }
1697 23
        if (isset(EvidenceList::$evidences[$evidence])) {
1698 16
            $evidencesInfo = EvidenceList::$evidences[$evidence];
1699 16
        }
1700 23
        return $evidencesInfo;
1701
    }
1702
1703
    /**
1704
     * Obtain name for current (or given) evidence path
1705
     *
1706
     * @param string $evidence Evidence Path
1707
     * @return array Evidence info
1708
     */
1709 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...
1710
    {
1711 23
        $evidenceName = null;
1712 23
        if (is_null($evidence)) {
1713 23
            $evidence = $this->getEvidence();
1714 23
        }
1715 23
        if (isset(EvidenceList::$name[$evidence])) {
1716 16
            $evidenceName = EvidenceList::$name[$evidence];
1717 16
        }
1718 23
        return $evidenceName;
1719
    }
1720
1721
    /**
1722
     * Perform given action (if availble) on current evidence/record
1723
     * @url https://demo.flexibee.eu/devdoc/actions
1724
     *
1725
     * @param string $action one of evidence actions
1726
     * @param string $method ext|int External method call operation in URL.
1727
     *                               Internal add the @action element to request body
1728
     */
1729 23
    public function performAction($action, $method = 'ext')
1730
    {
1731 23
        $actionsAvailble = $this->getActionsInfo();
1732
1733 23
        if (is_array($actionsAvailble) && array_key_exists($action,
1734 23
                $actionsAvailble)) {
1735 15
            switch ($actionsAvailble[$action]['actionMakesSense']) {
1736 15
                case 'ONLY_WITH_INSTANCE_AND_NOT_IN_EDIT':
1737 15
                case 'ONLY_WITH_INSTANCE': //Add instance
1738 4
                    $urlSuffix = '/'.$this->__toString().'/'.$action.'.'.$this->format;
1739 4
                    break;
1740
1741 15
                default:
1742 15
                    $urlSuffix = '/'.$action;
1743 15
                    break;
1744 15
            }
1745
1746
            switch ($method) {
1747 15
                case 'int':
1748
                    $this->setAction($action);
1749
                    $this->setPostFields($this->jsonizeData($this->getData()));
1750
                    $result = $this->performRequest(null, 'POST');
1751
                    break;
1752
1753 15
                default:
1754 15
                    $result = $this->performRequest($this->evidenceUrlWithSuffix($urlSuffix),
1755 15
                        'GET');
1756 15
                    break;
1757 15
            }
1758 15
        } else {
1759 19
            throw new \Exception(sprintf(_('Unsupported action %s for evidence %s'),
1760 19
                    $action, $this->getEvidence()));
1761
        }
1762
1763 15
        return $result;
1764
    }
1765
1766
    /**
1767
     * Save current object to file
1768
     *
1769
     * @param string $destfile path to file
1770
     */
1771 23
    public function saveResponseToFile($destfile)
1772
    {
1773 23
        if (strlen($this->lastCurlResponse)) {
1774 1
            $this->doCurlRequest($this->apiURL, 'GET', $this->format);
1775 1
        }
1776 23
        file_put_contents($destfile, $this->lastCurlResponse);
1777 23
    }
1778
1779
    /**
1780
     * Obtain established relations listing
1781
     *
1782
     * @return array Null or Relations
1783
     */
1784 9
    public function getVazby($id = null)
1785
    {
1786 9
        if (is_null($id)) {
1787 9
            $id = $this->getRecordID();
1788 9
        }
1789 9
        if (!empty($id)) {
1790 2
            $vazbyRaw = $this->getColumnsFromFlexibee(['vazby'],
1791 2
                ['relations' => 'vazby', 'id' => $id]);
1792 2
            $vazby    = array_key_exists('vazby', $vazbyRaw[0]) ? $vazbyRaw[0]['vazby']
1793 2
                    : null;
1794 2
        } else {
1795 9
            throw new \Exception(_('ID requied to get record relations '));
1796
        }
1797 2
        return $vazby;
1798
    }
1799
1800
    /**
1801
     * Gives You URL for Current Record in FlexiBee web interface
1802
     *
1803
     * @return string url
1804
     */
1805
    public function getFlexiBeeURL()
1806
    {
1807
        $parsed_url = parse_url(str_replace('.'.$this->format, '', $this->apiURL));
1808
        $scheme     = isset($parsed_url['scheme']) ? $parsed_url['scheme'].'://'
1809
                : '';
1810
        $host       = isset($parsed_url['host']) ? $parsed_url['host'] : '';
1811
        $port       = isset($parsed_url['port']) ? ':'.$parsed_url['port'] : '';
1812
        $user       = isset($parsed_url['user']) ? $parsed_url['user'] : '';
1813
        $pass       = isset($parsed_url['pass']) ? ':'.$parsed_url['pass'] : '';
1814
        $pass       = ($user || $pass) ? "$pass@" : '';
1815
        $path       = isset($parsed_url['path']) ? $parsed_url['path'] : '';
1816
        return $scheme.$user.$pass.$host.$port.$path;
1817
    }
1818
1819
    /**
1820
     * Set Record Key
1821
     *
1822
     * @param int|string $myKeyValue
1823
     * @return boolean
1824
     */
1825
    public function setMyKey($myKeyValue)
1826
    {
1827
        $res = parent::setMyKey($myKeyValue);
1828
        $this->updateApiURL();
1829
        return $res;
1830
    }
1831
1832
    /**
1833
     * Set or get ignore not found pages flag
1834
     *
1835
     * @param boolean $ignore set flag to
1836
     *
1837
     * @return boolean get flag state
1838
     */
1839
    public function ignore404($ignore = null)
1840
    {
1841
        if (!is_null($ignore)) {
1842
            $this->ignoreNotFound = $ignore;
1843
        }
1844
        return $this->ignoreNotFound;
1845
    }
1846
1847
    /**
1848
     * Send Document by mail
1849
     *
1850
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
1851
     *
1852
     * @param string $to
1853
     * @param string $subject
1854
     * @param string $body Email Text
1855
     *
1856
     * @return int http response code
1857
     */
1858
    public function sendByMail($to, $subject, $body, $cc = null)
1859
    {
1860
        $this->setPostFields($body);
1861
        $result = $this->doCurlRequest(urlencode($this->getRecordID()).'/odeslani-dokladu?to='.$to.'&subject='.urlencode($subject).'&cc='.$cc
1862
            , 'PUT', 'xml');
1863
        return $result == 200;
1864
    }
1865
1866
    /**
1867
     * Send all unsent Invoices by mail
1868
     *
1869
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
1870
     * @return int http response code
1871
     */
1872
    public function sendUnsent()
1873
    {
1874
        return $this->doCurlRequest('automaticky-odeslat-neodeslane', 'PUT',
1875
                'xml');
1876
    }
1877
1878
    /**
1879
     * FlexiBee date to PHP DateTime conversion
1880
     *
1881
     * @param string $flexidate 2017-05-26+02:00
1882
     *
1883
     * @return \DateTime | false
1884
     */
1885 23
    public static function flexiDateToDateTime($flexidate)
1886
    {
1887 23
        return \DateTime::createFromFormat('Y-m-dO', $flexidate)->setTime(0, 0);
1888
    }
1889
1890
    /**
1891
     * FlexiBee dateTime to PHP DateTime conversion
1892
     *
1893
     * @param string $flexidatetime 2017-09-26T10:00:53.755+02:00
1894
     *
1895
     * @return \DateTime | false
1896
     */
1897 23
    public static function flexiDateTimeToDateTime($flexidatetime)
1898
    {
1899 23
        return \DateTime::createFromFormat('Y-m-j\TH:i:s.u+P', $flexidatetime);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression \DateTime::createFromFor....u+P', $flexidatetime); of type DateTime|false adds false to the return on line 1899 which is incompatible with the return type documented by FlexiPeeHP\FlexiBeeRO::flexiDateTimeToDateTime of type DateTime. It seems like you forgot to handle an error condition.
Loading history...
1900
    }
1901
1902
    /**
1903
     * Získá dokument v daném formátu
1904
     * Obtain document in given format
1905
     *
1906
     * @param string $format  pdf/csv/xml/json/ ...
1907
     * @param string $reportName Template used to generate PDF
0 ignored issues
show
Bug introduced by
There is no parameter named $reportName. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
1908
     *
1909
     * @return string|null filename downloaded or none
1910
     */
1911
    public function getInFormat($format)
1912
    {
1913
        $response = null;
1914
        if ($this->setFormat($format)) {
1915
            $urlParams = [];
1916
            if (!empty($reportName)) {
0 ignored issues
show
Bug introduced by
The variable $reportName seems to never exist, and therefore empty should always return true. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
1917
                $urlParams['report-name'] = $reportName;
1918
            }
1919
            if ($format == 'html') {
1920
                $urlParams['inDesktopApp'] = 'true';
1921
            }
1922
            if (($this->doCurlRequest($this->addUrlParams($this->apiURL,
1923
                        $urlParams), 'GET') == 200)) {
1924
                $response = $this->lastCurlResponse;
1925
            }
1926
        }
1927
        return $response;
1928
    }
1929
1930
    /**
1931
     * Uloží dokument v daném formátu do složky v systému souborů
1932
     * Save document in given format to directory in filesystem
1933
     *
1934
     * @param string $format  pdf/csv/xml/json/ ...
1935
     * @param string $destDir where to put file (prefix)
1936
     * @param string $reportName Template used to generate PDF
1937
     *
1938
     * @return string|null filename downloaded or none
1939
     */
1940
    public function downloadInFormat($format, $destDir = './',
1941
                                     $reportName = null)
1942
    {
1943
        $fileOnDisk   = null;
1944
        $formatBackup = $this->format;
1945
        if ($this->setFormat($format)) {
1946
            $downloadTo = $destDir.$this->getEvidence().'_'.$this->getMyKey().'.'.$format;
1947
            if (($this->doCurlRequest(empty($reportName) ? $this->apiURL : $this->addUrlParams($this->apiURL,
1948
                            ['report-name' => $reportName]), 'GET') == 200) && (file_put_contents($downloadTo,
1949
                    $this->lastCurlResponse) !== false)) {
1950
                $fileOnDisk = $downloadTo;
1951
            }
1952
            $this->setFormat($formatBackup);
1953
        }
1954
        return $fileOnDisk;
1955
    }
1956
1957
    /**
1958
     * Compile and send Report about Error500 to FlexiBee developers
1959
     * If FlexiBee is running on localost try also include java backtrace
1960
     *
1961
     * @param array $errorResponse result of parseError();
1962
     */
1963
    public function error500Reporter($errorResponse)
1964
    {
1965
        $ur = str_replace('/c/'.$this->company, '',
1966
            str_replace($this->url, '', $this->curlInfo['url']));
1967
        if (!array_key_exists($ur, $this->reports)) {
1968
            $tmpdir   = sys_get_temp_dir();
1969
            $myTime   = $this->curlInfo['when'];
1970
            $curlname = $tmpdir.'/curl-'.$this->evidence.'-'.$myTime.'.json';
1971
            file_put_contents($curlname,
1972
                json_encode($this->curlInfo, JSON_PRETTY_PRINT));
1973
1974
            $report = new \Ease\Mailer($this->reportRecipient,
1975
                'Error report 500 - '.$ur);
1976
1977
            $d     = dir($tmpdir);
1978
            while (false !== ($entry = $d->read())) {
1979
                if (strstr($entry, $myTime)) {
1980
                    $ext  = pathinfo($tmpdir.'/'.$entry, PATHINFO_EXTENSION);
1981
                    $mime = Formats::suffixToContentType($ext);
1982
                    $report->addFile($tmpdir.'/'.$entry,
1983
                        empty($mime) ? 'text/plain' : $mime);
1984
                }
1985
            }
1986
            $d->close();
1987
1988
            if ((strstr($this->url, '://localhost') || strstr($this->url,
1989
                    '://127.')) && file_exists('/var/log/flexibee.log')) {
1990
1991
                $fl = fopen("/var/log/flexibee.log", "r");
1992
                if ($fl) {
1993
                    $tracelog = [];
1994
                    for ($x_pos = 0, $ln = 0, $output = array(); fseek($fl,
1995
                            $x_pos, SEEK_END) !== -1; $x_pos--) {
1996
                        $char = fgetc($fl);
1997
                        if ($char === "\n") {
1998
                            $tracelog[] = $output[$ln];
1999
                            if (strstr($output[$ln], $errorResponse['message'])) {
2000
                                break;
2001
                            }
2002
                            $ln++;
2003
                            continue;
2004
                        }
2005
                        $output[$ln] = $char.((array_key_exists($ln, $output)) ? $output[$ln]
2006
                                : '');
2007
                    }
2008
2009
                    $trace     = implode("\n", array_reverse($tracelog));
2010
                    $tracefile = $tmpdir.'/trace-'.$this->evidence.'-'.$myTime.'.log';
2011
                    file_put_contents($tracefile, $trace);
2012
                    $report->addItem("\n\n".$trace);
2013
                    fclose($fl);
2014
                }
2015
            } else {
2016
                $report->addItem($errorResponse['message']);
2017
            }
2018
2019
            $licenseInfo = $this->performRequest($this->url.'/default-license.json');
2020
2021
            $report->addItem("\n\n".json_encode($licenseInfo['license'],
2022
                    JSON_PRETTY_PRINT));
2023
2024
            if ($report->send()) {
2025
                $this->reports[$ur] = $myTime;
2026
            }
2027
        }
2028
    }
2029
2030
    /**
2031
     * Returns code:CODE
2032
     *
2033
     * @param string $code
2034
     *
2035
     * @return string
2036
     */
2037 8
    public static function code($code)
2038
    {
2039 8
        return 'code:'.self::uncode($code);
2040
    }
2041
2042
    /**
2043
     * Returns CODE without code: prefix
2044
     *
2045
     * @param string $code
2046
     *
2047
     * @return string
2048
     */
2049 8
    public static function uncode($code)
2050
    {
2051 8
        return str_replace(['code:', 'code%3A'], '', $code);
2052
    }
2053
2054
    /**
2055
     * Remove all @ items from array
2056
     *
2057
     * @param array $data original data
2058
     *
2059
     * @return array data without @ columns
2060
     */
2061
    public static function arrayCleanUP($data)
2062
    {
2063
        return array_filter(
2064
            $data,
2065
            function ($key) {
2066
            return !strchr($key, '@');
2067
        }, ARRAY_FILTER_USE_KEY);
2068
    }
2069
2070
    /**
2071
     * Add Info about used user, server and libraries
2072
     *
2073
     * @param string $additions Additional note text
2074
     */
2075 23
    function logBanner($additions = null)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
2076
    {
2077 23
        $this->addStatusMessage('FlexiBee '.str_replace('://',
2078 23
                '://'.$this->user.'@', str_replace('.json', '', $this->apiURL)).' FlexiPeeHP v'.self::$libVersion.' (FlexiBee '.EvidenceList::$version.') EasePHP Framework v'.\Ease\Atom::$frameworkVersion.' '.$additions,
2079 23
            'debug');
2080 23
    }
2081
2082
    /**
2083
     * Reconnect After unserialization
2084
     */
2085
    public function __wakeup()
2086
    {
2087
        parent::__wakeup();
2088
        $this->curlInit();
2089
    }
2090
}
2091