Test Failed
Push — master ( 0a6b17...c396e6 )
by Vítězslav
07:31
created

FlexiBeeRO::evidenceUrlWithSuffix()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 8
nc 3
nop 1
dl 0
loc 12
ccs 10
cts 10
cp 1
crap 5
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
     * 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 71
    public function setUp($options = [])
359
    {
360 71
        $this->setupProperty($options, 'company', 'FLEXIBEE_COMPANY');
361 71
        $this->setupProperty($options, 'url', 'FLEXIBEE_URL');
362 71
        $this->setupProperty($options, 'user', 'FLEXIBEE_LOGIN');
363 71
        $this->setupProperty($options, 'password', 'FLEXIBEE_PASSWORD');
364 71
        if (isset($options['evidence'])) {
365 23
            $this->setEvidence($options['evidence']);
366 23
        }
367 71
        $this->setupProperty($options, 'defaultUrlParams');
368 71
        if (isset($options['prefix'])) {
369 23
            $this->setPrefix($options['prefix']);
370 23
        }
371 71
        if (array_key_exists('detail', $options)) {
372
            $this->defaultUrlParams['detail'] = $options['detail'];
373
        }
374 71
        $this->setupProperty($options, 'debug');
375 71
        $this->updateApiURL();
376 71
    }
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 48
    public function setupProperty($options, $name, $constant = null)
386
    {
387 48
        if (isset($options[$name])) {
388
            $this->$name = $options[$name];
389
        } else {
390 48
            if (property_exists($this, $name) && !empty($constant) && defined($constant)) {
391 48
                $this->$name = constant($constant);
392 48
            }
393
        }
394 48
    }
395
396
    /**
397
     * Inicializace CURL
398
     */
399 94
    public function curlInit()
400
    {
401 94
        $this->curl = \curl_init(); // create curl resource
402 94
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); // return content as a string from curl_exec
403 94
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true); // follow redirects (compatibility for future changes in FlexiBee)
404 94
        curl_setopt($this->curl, CURLOPT_HTTPAUTH, true);       // HTTP authentication
405 94
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); // FlexiBee by default uses Self-Signed certificates
406 94
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
407 94
        curl_setopt($this->curl, CURLOPT_VERBOSE, ($this->debug === true)); // For debugging
408 94
        curl_setopt($this->curl, CURLOPT_USERPWD,
409 94
            $this->user.':'.$this->password); // set username and password
410 94
    }
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 13
    public function processInit($init)
424
    {
425 13
        if (is_integer($init)) {
426 10
            $this->loadFromFlexiBee($init);
427 13
        } elseif (is_array($init)) {
428 13
            $this->takeData($init);
429 13
        } 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 10
        } else {
433 8
            $this->loadFromFlexiBee($init);
434
        }
435 13
    }
436
437
    /**
438
     * Set URL prefix
439
     *
440
     * @param string $prefix
441
     */
442 23
    public function setPrefix($prefix)
443
    {
444
        switch ($prefix) {
445 23
            case 'a': //Access
446 23
            case 'c': //Company
447 23
            case 'u': //User
448 23
            case 'g': //License Groups
449 23
            case 'admin':
450 23
            case 'status':
451 23
            case 'login-logout':
452 23
                $this->prefix = '/'.$prefix.'/';
453 23
                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 23
    }
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 23
    public function setEvidence($evidence)
495
    {
496 23
        switch ($this->prefix) {
497 23
            case '/c/':
498 23
                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 20
                    $this->evidence = $evidence;
508 20
                    $result         = true;
509
                }
510 20
                break;
511 3
            default:
512 3
                $this->evidence = $evidence;
513 3
                $result         = true;
514 3
                break;
515 23
        }
516 23
        $this->updateApiURL();
517 23
        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 69
    public function getEvidence()
527
    {
528 69
        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 25
    public function getResponseEvidence()
559
    {
560 25
        switch ($this->evidence) {
561 25
            case 'c':
562
                $evidence = 'company';
563
                break;
564 25
            case 'evidence-list':
565 1
                $evidence = 'evidence';
566 1
                break;
567 24
            default:
568 24
                $evidence = $this->getEvidence();
569 24
                break;
570 25
        }
571 25
        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 22
            $resultID = $object->__toString();
614 22
        } else {
615 23
            if (is_array($object)) {
616 17
                foreach ($object as $item => $value) {
617 17
                    $resultID[$item] = self::objectToID($value);
618 17
                }
619 17
            } else { //String
620 23
                $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 68
    public function getEvidenceURL()
635
    {
636 68
        $evidenceUrl = $this->url.$this->prefix.$this->company;
637 68
        $evidence    = $this->getEvidence();
638 68
        if (!empty($evidence)) {
639 62
            $evidenceUrl .= '/'.$evidence;
640 62
        }
641 68
        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 48
    public function updateApiURL()
668
    {
669 48
        $this->apiURL = $this->getEvidenceURL();
670 48
        $id           = $this->__toString();
671 48
        if (!empty($id)) {
672
            $this->apiURL .= '/'.urlencode($id);
673
        }
674 48
        $this->apiURL .= '.'.$this->format;
675 48
    }
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 25
    public function performRequest($urlSuffix = null, $method = 'GET',
732
                                   $format = null)
733
    {
734 25
        $this->rowCount = null;
735
736 25
        if (preg_match('/^http/', $urlSuffix)) {
737
            $url = $urlSuffix;
738 25
        } elseif (strlen($urlSuffix) && ($urlSuffix[0] == '/')) {
739 4
            $url = $this->url.$urlSuffix;
740 4
        } else {
741 22
            $url = $this->evidenceUrlWithSuffix($urlSuffix);
742
        }
743
744 25
        $responseCode = $this->doCurlRequest($url, $method, $format);
745
746 25
        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 25
                    $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 3
    public function rawResponseToArray($responseRaw, $format)
759
    {
760 3
        if (!empty(trim($responseRaw))) {
761
            switch ($format) {
762 3
                case 'json':
763 3
                    $responseDecoded = $this->rawJsonToArray($responseRaw);
764 3
                    break;
765
                case 'xml':
766
                    $responseDecoded = $this->rawXmlToArray($this->lastCurlResponse);
767
                    break;
768
                case 'txt':
769
                default:
770
                    $responseDecoded = $this->lastCurlResponse;
771
                    break;
772
            }
773 3
        }
774
775 3
        return $responseDecoded;
0 ignored issues
show
Bug introduced by
The variable $responseDecoded does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

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