Test Failed
Push — master ( d9a263...a5f1c5 )
by Vítězslav
07:08
created

FlexiBeeRO::setDataValue()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5.025

Importance

Changes 0
Metric Value
cc 5
eloc 14
nc 5
nop 2
dl 0
loc 19
ccs 9
cts 10
cp 0.9
crap 5.025
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.4.2.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
     * Formating string for \DateTime::format() for datetime columns
336
     * @var string 
337
     */
338
    static public $DateTimeFormat = 'Y-m-d\TH:i:s.u+P';
339
340 70
    /**
341
     * Formating string for \DateTime::format() for date columns
342 70
     * @var string 
343
     */
344 70
    static public $DateFormat = 'Y-m-dO';
345 70
346 70
    /**
347 70
     * Class for read only interaction with FlexiBee.
348 22
     *
349 22
     * @param mixed $init default record id or initial data
350 70
     * @param array $options Connection settings override
351
     */
352
    public function __construct($init = null, $options = [])
353
    {
354
        $this->init = $init;
355
356
        parent::__construct();
357
        $this->setUp($options);
358 71
        $this->curlInit();
359
        if (!empty($init)) {
360 71
            $this->processInit($init);
361 71
        }
362 71
    }
363 71
364 71
    /**
365 23
     * SetUp Object to be ready for connect
366 23
     *
367 71
     * @param array $options Object Options (company,url,user,password,evidence,
368 71
     *                                       prefix,defaultUrlParams,debug)
369 23
     */
370 23
    public function setUp($options = [])
371 71
    {
372
        $this->setupProperty($options, 'company', 'FLEXIBEE_COMPANY');
373
        $this->setupProperty($options, 'url', 'FLEXIBEE_URL');
374 71
        $this->setupProperty($options, 'user', 'FLEXIBEE_LOGIN');
375 71
        $this->setupProperty($options, 'password', 'FLEXIBEE_PASSWORD');
376 71
        if (isset($options['evidence'])) {
377
            $this->setEvidence($options['evidence']);
378
        }
379
        $this->setupProperty($options, 'defaultUrlParams');
380
        if (isset($options['prefix'])) {
381
            $this->setPrefix($options['prefix']);
382
        }
383
        if (array_key_exists('detail', $options)) {
384
            $this->defaultUrlParams['detail'] = $options['detail'];
385 48
        }
386
        $this->setupProperty($options, 'debug');
387 48
        $this->updateApiURL();
388
    }
389
390 48
    /**
391 48
     * Set up one of properties
392 48
     *
393
     * @param array  $options  array of given properties
394 48
     * @param string $name     name of property to process
395
     * @param string $constant load default property value from constant
396
     */
397
    public function setupProperty($options, $name, $constant = null)
398
    {
399 94
        if (isset($options[$name])) {
400
            $this->$name = $options[$name];
401 94
        } else {
402 94
            if (property_exists($this, $name) && !empty($constant) && defined($constant)) {
403 94
                $this->$name = constant($constant);
404 94
            }
405 94
        }
406 94
    }
407 94
408 94
    /**
409 94
     * Inicializace CURL
410 94
     */
411
    public function curlInit()
412
    {
413
        $this->curl = \curl_init(); // create curl resource
414
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); // return content as a string from curl_exec
415
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true); // follow redirects (compatibility for future changes in FlexiBee)
416
        curl_setopt($this->curl, CURLOPT_HTTPAUTH, true);       // HTTP authentication
417
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); // FlexiBee by default uses Self-Signed certificates
418
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
419
        curl_setopt($this->curl, CURLOPT_VERBOSE, ($this->debug === true)); // For debugging
420
        curl_setopt($this->curl, CURLOPT_USERPWD,
421
            $this->user.':'.$this->password); // set username and password
422
    }
423 13
424
    /**
425 13
     * Zinicializuje objekt dle daných dat. Možné hodnoty:
426 10
     *
427 13
     *  * 234                              - interní číslo záznamu k načtení
428 13
     *  * code:LOPATA                      - kód záznamu
429 13
     *  * BAGR                             - kód záznamu k načtení
430 10
     *  * ['id'=>24,'nazev'=>'hoblík']     - pole hodnot k předvyplnění
431 10
     *  * 743.json?relations=adresa,vazby  - část url s parametry k načtení
432 10
     *
433 8
     * @param mixed $init číslo/"(code:)kód"/(část)URI záznamu k načtení | pole hodnot k předvyplnění
434
     */
435 13
    public function processInit($init)
436
    {
437
        if (is_integer($init)) {
438
            $this->loadFromFlexiBee($init);
439
        } elseif (is_array($init)) {
440
            $this->takeData($init);
441
        } elseif (preg_match('/\.(json|xml|csv)/', $init)) {
442 23
            $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...
443
                            : $init)));
444
        } else {
445 23
            $this->loadFromFlexiBee($init);
446 23
        }
447 23
    }
448 23
449 23
    /**
450 23
     * Set Data Field value
451 23
     *
452 23
     * @param string $columnName field name
453 23
     * @param mixed  $value      field data value
454 23
     *
455 23
     * @return bool Success
456 23
     */
457 23
    public function setDataValue($columnName, $value)
458 23
    {
459 23
        if (is_object($value)) {
460 23
            switch (get_class($value)) {
461 23
                case 'DateTime':
462 23
                    $columnInfo = $this->getColumnInfo($columnName);
463
                    switch ($columnInfo['type']) {
464
                        case 'date':
465
                            $value = $value->format(self::$DateFormat);
466
                            break;
467
                        case 'datetime':
468
                            $value = $value->format(self::$DateTimeFormat);
469
                            break;
470
                    }
471 23
                    break;
472
            }
473 23
        }
474 23
        return parent::setDataValue($columnName, $value);
475
    }
476
477
    /**
478
     * Set URL prefix
479
     *
480 23
     * @param string $prefix
481 23
     */
482 23
    public function setPrefix($prefix)
483 23
    {
484 23
        switch ($prefix) {
485
            case 'a': //Access
486
            case 'c': //Company
487
            case 'u': //User
488
            case 'g': //License Groups
489
            case 'admin':
490
            case 'status':
491
            case 'login-logout':
492
                $this->prefix = '/'.$prefix.'/';
493
                break;
494 23
            case null:
495
            case '':
496 23
            case '/':
497 23
                $this->prefix = '';
498 23
                break;
499 23
            default:
500
                throw new \Exception(sprintf('Unknown prefix %s', $prefix));
501
        }
502
    }
503 23
504 23
    /**
505
     * Set communication format.
506
     * One of html|xml|json|csv|dbf|xls|isdoc|isdocx|edi|pdf|pdf|vcf|ical
507 20
     *
508 20
     * @param string $format
509
     * @return boolen format is availble
510 20
     */
511 3
    public function setFormat($format)
512 3
    {
513 3
        $result = true;
514 3
        if (($this->debug === true) && !empty($this->evidence) && isset(Formats::$$this->evidence)) {
515 23
            if (array_key_exists($format, array_flip(Formats::$$this->evidence))
516 23
                === false) {
517 23
                $result = false;
518
            }
519
        }
520
        if ($result === true) {
521
            $this->format = $format;
522
            $this->updateApiURL();
523
        }
524
        return $result;
525
    }
526 69
527
    /**
528 69
     * Nastaví Evidenci pro Komunikaci.
529
     * Set evidence for communication
530
     *
531
     * @param string $evidence evidence pathName to use
532
     * @return boolean evidence switching status
533
     */
534
    public function setEvidence($evidence)
535
    {
536
        switch ($this->prefix) {
537 23
            case '/c/':
538
                if ($this->debug === true) {
539 23
                    if (array_key_exists($evidence, EvidenceList::$name)) {
540 23
                        $this->evidence = $evidence;
541
                        $result         = true;
542
                    } else {
543
                        throw new \Exception(sprintf('Try to set unsupported evidence %s',
544
                                $evidence));
545
                    }
546
                } else {
547
                    $this->evidence = $evidence;
548 23
                    $result         = true;
549
                }
550 23
                break;
551
            default:
552
                $this->evidence = $evidence;
553
                $result         = true;
554
                break;
555
        }
556
        $this->updateApiURL();
557
        return $result;
558 25
    }
559
560 25
    /**
561 25
     * Vrací právě používanou evidenci pro komunikaci
562
     * Obtain current used evidence
563
     *
564 25
     * @return string
565 1
     */
566 1
    public function getEvidence()
567 24
    {
568 24
        return $this->evidence;
569 24
    }
570 25
571 25
    /**
572
     * Set used company.
573
     * Nastaví Firmu.
574
     *
575
     * @param string $company
576
     */
577
    public function setCompany($company)
578
    {
579
        $this->company = $company;
580
    }
581 23
582
    /**
583 23
     * Obtain company now used
584 23
     * Vrací právě používanou firmu
585 23
     *
586 23
     * @return string
587 23
     */
588 23
    public function getCompany()
589 23
    {
590 23
        return $this->company;
591 23
    }
592 23
593 23
    /**
594 23
     * Vrací název evidence použité v odpovědích z FlexiBee
595 23
     *
596
     * @return string
597
     */
598
    public function getResponseEvidence()
599 23
    {
600
        switch ($this->evidence) {
601
            case 'c':
602
                $evidence = 'company';
603
                break;
604
            case 'evidence-list':
605
                $evidence = 'evidence';
606
                break;
607
            default:
608
                $evidence = $this->getEvidence();
609 23
                break;
610
        }
611 23
        return $evidence;
612 23
    }
613 22
614 22
    /**
615 23
     * Převede rekurzivně Objekt na pole.
616 17
     *
617 17
     * @param object|array $object
618 17
     *
619 17
     * @return array
620 23
     */
621
    public static function object2array($object)
622
    {
623
        $result = null;
624 23
        if (is_object($object)) {
625
            $objectData = get_object_vars($object);
626
            if (is_array($objectData) && count($objectData)) {
627
                $result = array_map('self::object2array', $objectData);
628
            }
629
        } else {
630
            if (is_array($object)) {
631
                foreach ($object as $item => $value) {
632
                    $result[$item] = self::object2array($value);
633
                }
634 68
            } else {
635
                $result = $object;
636 68
            }
637 68
        }
638 68
639 62
        return $result;
640 62
    }
641 68
642
    /**
643
     * Převede rekurzivně v poli všechny objekty na jejich identifikátory.
644
     *
645
     * @param object|array $object
646
     *
647
     * @return array
648
     */
649
    public static function objectToID($object)
650
    {
651 23
        $resultID = null;
652
        if (is_object($object)) {
653 23
            $resultID = $object->__toString();
654 23
        } else {
655 23
            if (is_array($object)) {
656 23
                foreach ($object as $item => $value) {
657 23
                    $resultID[$item] = self::objectToID($value);
658 23
                }
659 23
            } else { //String
660 23
                $resultID = $object;
661 23
            }
662
        }
663
664
        return $resultID;
665
    }
666
667 48
    /**
668
     * Return basic URL for used Evidence
669 48
     *
670 48
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
671 48
     *
672
     * @return string Evidence URL
673
     */
674 48
    public function getEvidenceURL()
675 48
    {
676
        $evidenceUrl = $this->url.$this->prefix.$this->company;
677
        $evidence    = $this->getEvidence();
678
        if (!empty($evidence)) {
679
            $evidenceUrl .= '/'.$evidence;
680
        }
681
        return $evidenceUrl;
682
    }
683
684
    /**
685
     * Add suffix to Evidence URL
686 23
     *
687
     * @param string $urlSuffix
688 23
     *
689 23
     * @return string
690 23
     */
691 23
    public function evidenceUrlWithSuffix($urlSuffix)
692 23
    {
693 23
        $evidenceUrl = $this->getEvidenceUrl();
694 23
        if (!empty($urlSuffix)) {
695 23
            if (($urlSuffix[0] != '/') && ($urlSuffix[0] != ';') && ($urlSuffix[0]
696 23
                != '?')) {
697 23
                $evidenceUrl .= '/';
698 23
            }
699 23
            $evidenceUrl .= $urlSuffix;
700 23
        }
701
        return $evidenceUrl;
702
    }
703 23
704 23
    /**
705 23
     * Update $this->apiURL
706
     */
707
    public function updateApiURL()
708 23
    {
709
        $this->apiURL = $this->getEvidenceURL();
710
        $id           = $this->__toString();
711
        if (!empty($id)) {
712
            $this->apiURL .= '/'.urlencode($id);
713
        }
714
        $this->apiURL .= '.'.$this->format;
715
    }
716
717
    /**
718 23
     * Add params to url
719
     *
720 23
     * @param string  $url      originall url
721
     * @param array   $params   value to add
722
     * @param boolean $override replace already existing values ?
723
     *
724
     * @return string url with parameters added
725
     */
726
    public function addUrlParams($url, $params, $override = false)
727
    {
728
        $urlParts = parse_url($url);
729
        $urlFinal = '';
730
        if (array_key_exists('scheme', $urlParts)) {
731 25
            $urlFinal .= $urlParts['scheme'].'://'.$urlParts['host'];
732
        }
733
        if (array_key_exists('port', $urlParts)) {
734 25
            $urlFinal .= ':'.$urlParts['port'];
735
        }
736 25
        if (array_key_exists('path', $urlParts)) {
737
            $urlFinal .= $urlParts['path'];
738 25
        }
739 4
        if (array_key_exists('query', $urlParts)) {
740 4
            parse_str($urlParts['query'], $queryUrlParams);
741 22
            $urlParams = $override ? array_merge($params, $queryUrlParams) : array_merge($queryUrlParams,
742
                    $params);
743
        } else {
744 25
            $urlParams = $params;
745
        }
746 25
747 25
        if (!empty($urlParams)) {
748
            $urlFinal .= '?';
749
            if (is_array($urlParams)) {
750
                $urlFinal .= http_build_query($urlParams);
751
            } else {
752
                $urlFinal .= $urlParams;
753
            }
754
        }
755
        return $urlFinal;
756
    }
757
758 3
    /**
759
     * Add Default Url params to given url if not overrided
760 3
     *
761
     * @param string $urlRaw
762 3
     *
763 3
     * @return string url with default params added
764 3
     */
765
    public function addDefaultUrlParams($urlRaw)
766
    {
767
        return $this->addUrlParams($urlRaw, $this->defaultUrlParams, false);
768
    }
769
770
    /**
771
     * Funkce, která provede I/O operaci a vyhodnotí výsledek.
772
     *
773 3
     * @param string $urlSuffix část URL za identifikátorem firmy.
774
     * @param string $method    HTTP/REST metoda
775 3
     * @param string $format    Requested format
776
     * @return array|boolean Výsledek operace
777
     */
778
    public function performRequest($urlSuffix = null, $method = 'GET',
779
                                   $format = null)
780
    {
781
        $this->rowCount = null;
782
783
        if (preg_match('/^http/', $urlSuffix)) {
784
            $url = $urlSuffix;
785 3
        } elseif (strlen($urlSuffix) && ($urlSuffix[0] == '/')) {
786
            $url = $this->url.$urlSuffix;
787 3
        } else {
788 3
            $url = $this->evidenceUrlWithSuffix($urlSuffix);
789 3
        }
790 3
791
        $responseCode = $this->doCurlRequest($url, $method, $format);
792
793 3
        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...
794
                    $this->responseFormat), $responseCode);
795
    }
796
797 3
    /**
798
     * Parse Raw FlexiBee response in several formats
799
     *
800
     * @param string $responseRaw raw response body
801
     * @param string $format      Raw Response format json|xml|etc
802
     *
803
     * @return array
804
     */
805
    public function rawResponseToArray($responseRaw, $format)
806
    {
807
        $responseDecoded = [];
808
        if (!empty(trim($responseRaw))) {
809
            switch ($format) {
810
                case 'json':
811
                    $responseDecoded = $this->rawJsonToArray($responseRaw);
812
                    break;
813
                case 'xml':
814
                    $responseDecoded = $this->rawXmlToArray($this->lastCurlResponse);
815
                    break;
816
                case 'txt':
817
                default:
818
                    $responseDecoded = $this->lastCurlResponse;
819
                    break;
820 3
            }
821
        }
822 3
        return $responseDecoded;
823
    }
824 3
825
    /**
826
     * Convert FlexiBee Response JSON to Array
827
     *
828
     * @param string $rawJson
829
     * 
830
     * @return array
831
     */
832 3
    public function rawJsonToArray($rawJson)
833 3
    {
834 3
        $responseDecoded = json_decode($rawJson, true, 10);
835
        $decodeError     = json_last_error_msg();
836
        if ($decodeError == 'No error') {
837 3
            if (array_key_exists($this->nameSpace, $responseDecoded)) {
838
                $responseDecoded = $responseDecoded[$this->nameSpace];
839
            }
840 3
        } else {
841
            $this->addStatusMessage('JSON Decoder: '.$decodeError, 'error');
842
            $this->addStatusMessage($rawJson, 'debug');
843
        }
844
        return $responseDecoded;
845
    }
846
847
    /**
848
     * Convert FlexiBee Response XML to Array
849
     *
850
     * @param string $rawXML
851
     *
852
     * @return array
853
     */
854
    public function rawXmlToArray($rawXML)
855
    {
856
        return self::xml2array($rawXML);
857
    }
858
859
    /**
860 3
     * Parse Response array
861
     *
862
     * @param array $responseDecoded
863
     * @param int $responseCode Request Response Code
864
     *
865
     * @return array main data part of response
866
     */
867
    public function parseResponse($responseDecoded, $responseCode)
868
    {
869
        $response = null;
870
        switch ($responseCode) {
871
            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...
872
                if (isset($responseDecoded[$this->resultField][0]['id'])) {
873
                    $this->lastInsertedID = $responseDecoded[$this->resultField][0]['id'];
874
                    $this->setMyKey($this->lastInsertedID);
875
                    $this->apiURL         = $this->getEvidenceURL().'/'.$this->lastInsertedID;
876
                } else {
877
                    $this->lastInsertedID = null;
878
                }
879
            case 200: //Success Read
880
                $response         = $this->lastResult = $this->unifyResponseFormat($responseDecoded);
881
                if (isset($responseDecoded['@rowCount'])) {
882
                    $this->rowCount = (int) $responseDecoded['@rowCount'];
883
                }
884
                if (isset($responseDecoded['@globalVersion'])) {
885
                    $this->globalVersion = (int) $responseDecoded['@globalVersion'];
886
                }
887
                break;
888
889
            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...
890 3
                if ($this->debug === true) {
891
                    $this->error500Reporter($responseDecoded);
892 3
                }
893 3
            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...
894 3
                if ($this->ignoreNotFound === true) {
895 3
                    break;
896
                }
897 3
            case 400: //Bad Request parameters
898
            default: //Something goes wrong
899 3
                $this->addStatusMessage($this->lastResponseCode.': '.$this->curlInfo['url'],
900
                    'warning');
901 3
                if (is_array($responseDecoded)) {
902
                    $this->parseError($responseDecoded);
903 3
                }
904
                $this->logResult($responseDecoded, $this->curlInfo['url']);
905 3
                break;
906 3
        }
907 3
        return $response;
908 3
    }
909 3
910 3
    /**
911 3
     * Parse error message response
912 3
     *
913 3
     * @param array $responseDecoded
914 3
     * @return int number of errors processed
915 3
     */
916 3
    public function parseError(array $responseDecoded)
917 3
    {
918
        if (array_key_exists('results', $responseDecoded)) {
919 3
            $this->errors = $responseDecoded['results'][0]['errors'];
920
        } else {
921
            if (array_key_exists('message', $responseDecoded)) {
922 3
                $this->errors = [['message' => $responseDecoded['message']]];
923 3
            }
924 3
        }
925 3
        return count($this->errors);
926 3
    }
927 3
928 3
    /**
929 3
     * Vykonej HTTP požadavek
930 3
     *
931
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
932
     * @param string $url    URL požadavku
933
     * @param string $method HTTP Method GET|POST|PUT|OPTIONS|DELETE
934
     * @param string $format požadovaný formát komunikace
935 3
     * @return int HTTP Response CODE
936
     */
937
    public function doCurlRequest($url, $method, $format = null)
938
    {
939 3
        if (is_null($format)) {
940
            $format = $this->format;
941
        }
942
        curl_setopt($this->curl, CURLOPT_URL, $url);
943
// Nastavení samotné operace
944
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
945
//Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411
946
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
947
948
        $httpHeaders = $this->defaultHttpHeaders;
949 23
950
        $formats = Formats::bySuffix();
951 23
952 23
        if (!isset($httpHeaders['Accept'])) {
953 23
            $httpHeaders['Accept'] = $formats[$format]['content-type'];
954 23
        }
955 15
        if (!isset($httpHeaders['Content-Type'])) {
956 15
            $httpHeaders['Content-Type'] = $formats[$format]['content-type'];
957 15
        }
958 23
        $httpHeadersFinal = [];
959
        foreach ($httpHeaders as $key => $value) {
960
            if (($key == 'User-Agent') && ($value == 'FlexiPeeHP')) {
961
                $value .= ' v'.self::$libVersion;
962
            }
963
            $httpHeadersFinal[] = $key.': '.$value;
964
        }
965
966
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
967
968 23
// Proveď samotnou operaci
969
        $this->lastCurlResponse            = curl_exec($this->curl);
970 23
        $this->curlInfo                    = curl_getinfo($this->curl);
971 23
        $this->curlInfo['when']            = microtime();
972 23
        $this->curlInfo['request_headers'] = $httpHeadersFinal;
973 23
        $this->responseFormat              = isset($this->curlInfo['content_type'])
974 23
                ? Formats::contentTypeToSuffix($this->curlInfo['content_type']) : 'txt';
975
        $this->lastResponseCode            = $this->curlInfo['http_code'];
976 23
        $this->lastCurlError               = curl_error($this->curl);
977 23
        if (strlen($this->lastCurlError)) {
978 23
            $this->addStatusMessage(sprintf('Curl Error (HTTP %d): %s',
979 23
                    $this->lastResponseCode, $this->lastCurlError), 'error');
980 23
        }
981
982 23
        if ($this->debug === true) {
983 23
            $this->saveDebugFiles();
984 23
        }
985
986
        return $this->lastResponseCode;
987
    }
988
989
    /**
990 1
     * Nastaví druh prováděné akce.
991
     *
992 1
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
993 1
     * @param string $action
994 1
     * @return boolean
995 1
     */
996 1
    public function setAction($action)
997
    {
998
        $result           = false;
999
        $actionsAvailable = $this->getActionsInfo();
1000
        if (is_array($actionsAvailable) && array_key_exists($action,
1001 1
                $actionsAvailable)) {
1002
            $this->action = $action;
1003 1
            $result       = true;
1004 1
        }
1005
        return $result;
1006
    }
1007
1008
    /**
1009
     * Convert XML to array.
1010
     *
1011
     * @param string $xml
1012
     *
1013 23
     * @return array
1014
     */
1015 23
    public static function xml2array($xml)
1016 23
    {
1017 22
        $arr = [];
1018
        if (!empty($xml)) {
1019
            if (is_string($xml)) {
1020
                $xml = simplexml_load_string($xml);
1021 22
            }
1022
1023
            foreach ($xml->children() as $r) {
1024
                if (count($r->children()) == 0) {
1025
                    $arr[$r->getName()] = strval($r);
1026
                } else {
1027
                    $arr[$r->getName()][] = self::xml2array($r);
1028
                }
1029
            }
1030
        }
1031
        return $arr;
1032
    }
1033
1034
    /**
1035
     * Odpojení od FlexiBee.
1036
     */
1037
    public function disconnect()
1038
    {
1039
        if (is_resource($this->curl)) {
1040
            curl_close($this->curl);
1041
        }
1042
        $this->curl = null;
1043
    }
1044
1045
    /**
1046
     * Disconnect CURL befere pass away
1047
     */
1048
    public function __destruct()
1049
    {
1050
        $this->disconnect();
1051
    }
1052
1053
    /**
1054
     * Načte řádek dat z FlexiBee.
1055
     *
1056
     * @param int $recordID id požadovaného záznamu
1057
     *
1058
     * @return array
1059 15
     */
1060
    public function getFlexiRow($recordID)
1061 15
    {
1062 15
        $record   = null;
1063
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
1064 15
        if (isset($response[$this->evidence])) {
1065 8
            $record = $response[$this->evidence][0];
1066 7
        }
1067 7
1068 7
        return $record;
1069
    }
1070 8
1071 1
    /**
1072 1
     * Oddělí z pole podmínek ty jenž patří za ? v URL požadavku
1073 8
     *
1074
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
1075 15
     * @param array $conditions pole podmínek   - rendrují se do ()
1076 4
     * @param array $urlParams  pole parametrů  - rendrují za ?
1077 4
     */
1078 4
    public function extractUrlParams(&$conditions, &$urlParams)
1079
    {
1080
        foreach ($this->urlParams as $urlParam) {
1081
            if (isset($conditions[$urlParam])) {
1082
                \Ease\Sand::divDataArray($conditions, $urlParams, $urlParam);
1083 4
            }
1084
        }
1085 15
    }
1086
1087 15
    /**
1088 15
     * convert unicode to entities
1089
     *
1090
     * @param string $urlRaw
1091 15
     * @return string
1092
     */
1093 15
    public static function urlEncode($urlRaw)
1094 15
    {
1095 15
        return str_replace(['%27'], ["'"], rawurlencode($urlRaw));
1096
    }
1097 15
1098
    /**
1099 15
     * Načte data z FlexiBee.
1100 15
     *
1101 15
     * @param string $suffix     dotaz
1102 9
     * @param string|array $conditions Volitelný filtrovací výraz
1103 9
     *
1104 6
     * @return array Data obtained
1105 6
     */
1106 9
    public function getFlexiData($suffix = null, $conditions = null)
1107 6
    {
1108
        $finalUrl  = '';
1109
        $urlParams = $this->defaultUrlParams;
1110 15
1111
        if (!empty($conditions)) {
1112
            if (is_array($conditions)) {
1113
                $this->extractUrlParams($conditions, $urlParams);
1114
                $conditions = $this->flexiUrl($conditions);
1115
            }
1116
1117
            if (strlen($conditions) && ($conditions[0] != '/')) {
1118
                $conditions = '('.self::urlEncode($conditions).')';
1119
            }
1120
        }
1121 23
1122
        if (strlen($suffix)) {
1123 23
            if (preg_match('/^http/', $suffix) || ($suffix[0] == '/') || is_numeric($suffix)) {
1124 23
                $finalUrl = $suffix;
1125 23
            } else {
1126 23
                if (preg_match('/^(code|ext):(.*)/', $suffix, $matches)) {
1127 23
                    $finalUrl = $matches[1].':'.rawurlencode($matches[2]);
1128
                }
1129
            }
1130
        }
1131 23
1132
        $finalUrl .= $conditions;
1133
1134
        if (count($urlParams)) {
1135 23
            if (strstr($finalUrl, '?')) {
1136 22
                $finalUrl .= '&';
1137 22
            } else {
1138 9
                $finalUrl .= '?';
1139 9
            }
1140 22
            $finalUrl .= http_build_query($urlParams, null, '&',
1141
                PHP_QUERY_RFC3986);
1142
        }
1143
1144
        $transactions = $this->performRequest($finalUrl, 'GET');
1145
1146
        $responseEvidence = $this->getResponseEvidence();
1147
        if (is_array($transactions) && array_key_exists($responseEvidence,
1148
                $transactions)) {
1149
            $result = $transactions[$responseEvidence];
1150
            if ((count($result) == 1) && (count(current($result)) == 0 )) {
1151 6
                $result = null; // Response is empty Array
1152
            }
1153
        } else {
1154 6
            $result = $transactions;
1155 6
        }
1156 6
1157 6
        return $result;
1158 6
    }
1159
1160 6
    /**
1161
     * Načte záznam z FlexiBee a uloží v sobě jeho data
1162
     * Read FlexiBee record and store it inside od object
1163
     *
1164
     * @param int $id ID or conditions
1165 6
     *
1166
     * @return int počet načtených položek
1167
     */
1168
    public function loadFromFlexiBee($id = null)
1169 6
    {
1170
        $data = [];
1171
        if (is_null($id)) {
1172
            $id = $this->getMyKey();
1173
        }
1174
        if (is_array($id)) {
1175
            $id = rawurlencode('('.self::flexiUrl($id).')');
1176
        }
1177 16
1178
        if (preg_match('/^code/', $id)) {
1179 16
            $id = self::code(rawurlencode(self::uncode($id)));
1180 9
        }
1181 9
1182 16
        $flexidata    = $this->getFlexiData($this->getEvidenceUrl().'/'.$id);
1183 16
        $this->apiURL = $this->curlInfo['url'];
1184 16
        if (is_array($flexidata) && (count($flexidata) == 1)) {
1185
            $data = current($flexidata);
1186 16
        }
1187 16
        return $this->takeData($data);
1188 16
    }
1189 15
1190 15
    /**
1191
     * Převede data do Json formátu pro FlexiBee.
1192
     * Convert data to FlexiBee like Json format
1193
     * 
1194
     * @url https://www.flexibee.eu/api/dokumentace/ref/actions/
1195
     * @url https://www.flexibee.eu/api/dokumentace/ref/zamykani-odemykani/
1196
     *
1197
     * @param array $data
1198
     *
1199 15
     * @return string
1200
     */
1201
    public function jsonizeData($data)
1202 15
    {
1203 10
        $dataToJsonize = [
1204 10
            $this->nameSpace => [
1205 15
                '@version' => $this->protoVersion,
1206 15
                $this->evidence => $this->objectToID($data),
1207 15
            ],
1208 15
        ];
1209
1210 14 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...
1211 14
            $dataToJsonize[$this->nameSpace][$this->evidence.'@action'] = $this->action;
1212 14
            $this->action                                               = null;
1213 14
        }
1214 10
1215 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...
1216 14
            $dataToJsonize[$this->nameSpace][$this->evidence.'@filter'] = $this->filter;
1217 14
        }
1218
1219
        return json_encode($dataToJsonize);
1220
    }
1221
1222
    /**
1223
     * Test if given record ID exists in FlexiBee.
1224
     *
1225
     * @param boolean $identifer presence state
1226
     */
1227
    public function idExists($identifer = null)
1228
    {
1229
        if (is_null($identifer)) {
1230
            $identifer = $this->getMyKey();
1231
        }
1232
        $ignorestate = $this->ignore404();
1233
        $this->ignore404(true);
1234
        $this->getFlexiData(null,
1235
            [
1236
                'detail' => 'custom:'.$this->getmyKeyColumn(),
1237
                $this->getmyKeyColumn() => $identifer
1238
        ]);
1239
        $this->ignore404($ignorestate);
1240
        return $this->lastResponseCode == 200;
1241
    }
1242
1243
    /**
1244
     * Test if given record exists in FlexiBee.
1245
     *
1246
     * @param array $data
1247
     * @return boolean Record presence status
1248
     */
1249
    public function recordExists($data = [])
1250
    {
1251
1252 15
        if (empty($data)) {
1253
            $data = $this->getData();
1254
        }
1255 15
        $ignorestate = $this->ignore404();
1256 15
        $this->ignore404(true);
1257 15
        $res         = $this->getColumnsFromFlexibee([$this->getKeyColumn()],
0 ignored issues
show
Bug introduced by
The method getKeyColumn() does not exist on FlexiPeeHP\FlexiBeeRO. Did you maybe mean getmyKeyColumn()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
1258
            [self::flexiUrl($data)]);
1259 15
1260 15
        if (!count($res) || (isset($res['success']) && ($res['success'] == 'false'))
1261 15
            || !count($res[0])) {
1262 15
            $found = false;
1263 15
        } else {
1264 15
            $found = true;
1265 15
        }
1266 15
        $this->ignore404($ignorestate);
1267
        return $found;
1268 15
    }
1269
1270
    /**
1271 15
     * Vrací z FlexiBee sloupečky podle podmínek.
1272
     *
1273
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
1274 15
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
1275 15
     *                                     sloupečku
1276 15
     * @return array
1277 15
     */
1278 15
    public function getAllFromFlexibee($conditions = null, $indexBy = null)
1279
    {
1280 15
        if (is_int($conditions)) {
1281
            $conditions = [$this->getmyKeyColumn() => $conditions];
1282 15
        }
1283
1284 15
        $flexiData = $this->getFlexiData('', $conditions);
1285 9
1286 9
        if (!is_null($indexBy)) {
1287
            $flexiData = $this->reindexArrayBy($flexiData);
1288 15
        }
1289
1290
        return $flexiData;
1291
    }
1292
1293
    /**
1294
     * Vrací z FlexiBee sloupečky podle podmínek.
1295
     *
1296
     * @param string[] $columnsList seznam položek
1297
     * @param array    $conditions  pole podmínek nebo ID záznamu
1298
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
1299 23
     *
1300
     * @return array
1301 23
     */
1302
    public function getColumnsFromFlexibee($columnsList, $conditions = [],
1303 23
                                           $indexBy = null)
1304 23
    {
1305 23
        $detail = 'full';
1306
        switch (gettype($columnsList)) {
1307 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...
1308 23
                $conditions = [$this->getmyKeyColumn() => $conditions];
1309 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...
1310
                if (!is_null($indexBy) && !array_key_exists($indexBy,
1311 23
                        $columnsList)) {
1312 23
                    $columnsList[] = $indexBy;
1313 23
                }
1314 23
                $columns = implode(',', array_unique($columnsList));
1315 23
                $detail  = 'custom:'.$columns;
1316 23
            default:
1317 23
                switch ($columnsList) {
1318 23
                    case 'id':
1319 23
                        $detail = 'id';
1320 23
                        break;
1321
                    case 'summary':
1322
                        $detail = 'summary';
1323
                        break;
1324 23
                    default:
1325 23
                        break;
1326 23
                }
1327
                break;
1328 23
        }
1329 23
1330 23
        $conditions['detail'] = $detail;
1331 23
1332
        $flexiData = $this->getFlexiData(null, $conditions);
1333
1334 23
        if (!is_null($indexBy) && count($flexiData) && count(current($flexiData))) {
1335 23
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
1336 23
        }
1337 23
1338 23
        return $flexiData;
1339 23
    }
1340 23
1341 23
    /**
1342 23
     * Vrací kód záznamu.
1343 23
     * Obtain record CODE
1344 23
     *
1345 23
     * @param mixed $data
1346
     *
1347 23
     * @return string
1348 23
     */
1349
    public function getKod($data = null, $unique = true)
1350 23
    {
1351
        $kod = null;
1352
1353
        if (is_null($data)) {
1354
            $data = $this->getData();
1355
        }
1356
1357
        if (is_string($data)) {
1358
            $data = [$this->nameColumn => $data];
1359
        }
1360 23
1361
        if (isset($data['kod'])) {
1362 23
            $kod = $data['kod'];
1363 23
        } else {
1364 23
            if (isset($data[$this->nameColumn])) {
1365
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
1366
                    \Ease\Sand::rip($data[$this->nameColumn]));
1367 23
            } else {
1368 23
                if (isset($data[$this->myKeyColumn])) {
1369 23
                    $kod = \Ease\Sand::rip($data[$this->myKeyColumn]);
1370 23
                }
1371 23
            }
1372
        }
1373
1374 23
        if (!strlen($kod)) {
1375 23
            $kod = 'NOTSET';
1376 23
        }
1377
1378 23
        if (strlen($kod) > 18) {
1379 23
            $kodfinal = strtoupper(substr($kod, 0, 18));
1380 23
        } else {
1381 23
            $kodfinal = strtoupper($kod);
1382 23
        }
1383
1384 23
        if ($unique) {
1385 23
            $counter = 0;
1386 23
            if (count($this->codes)) {
1387 23
                foreach ($this->codes as $codesearch => $keystring) {
1388 23
                    if (strstr($codesearch, $kodfinal)) {
1389
                        ++$counter;
1390 23
                    }
1391 23
                }
1392 23
            }
1393 23
            if ($counter) {
1394
                $kodfinal = $kodfinal.$counter;
1395
            }
1396 23
1397
            $this->codes[$kodfinal] = $kod;
1398
        }
1399 23
1400
        return self::code($kodfinal);
1401
    }
1402 23
1403 23
    /**
1404 23
     * Write Operation Result.
1405 23
     *
1406 23
     * @param array  $resultData
1407 23
     * @param string $url        URL
1408
     * @return boolean Log save success
1409
     */
1410
    public function logResult($resultData = null, $url = null)
1411
    {
1412
        $logResult = false;
1413
        if (isset($resultData['success']) && ($resultData['success'] == 'false')) {
1414
            if (isset($resultData['message'])) {
1415
                $this->addStatusMessage($resultData['message'], 'warning');
1416
            }
1417
            $this->addStatusMessage('Error '.$this->lastResponseCode.': '.urldecode($url),
1418
                'warning');
1419
            unset($url);
1420
        }
1421
        if (is_null($resultData)) {
1422
            $resultData = $this->lastResult;
1423
        }
1424
        if (isset($url)) {
1425
            $this->logger->addStatusMessage($this->lastResponseCode.':'.urldecode($url));
1426
        }
1427
1428
        if (isset($resultData['results'])) {
1429
            if ($resultData['success'] == 'false') {
1430
                $status = 'error';
1431
            } else {
1432
                $status = 'success';
1433
            }
1434
            foreach ($resultData['results'] as $result) {
1435
                if (isset($result['request-id'])) {
1436
                    $rid = $result['request-id'];
1437
                } else {
1438
                    $rid = '';
1439
                }
1440
                if (isset($result['errors'])) {
1441
                    foreach ($result['errors'] as $error) {
1442
                        $message = $error['message'];
1443
                        if (isset($error['for'])) {
1444 23
                            $message .= ' for: '.$error['for'];
1445
                        }
1446 23
                        if (isset($error['value'])) {
1447
                            $message .= ' value:'.$error['value'];
1448 23
                        }
1449 23
                        if (isset($error['code'])) {
1450 23
                            $message .= ' code:'.$error['code'];
1451 23
                        }
1452 23
                        $this->addStatusMessage($rid.': '.$message, $status);
1453 23
                    }
1454 23
                }
1455 23
            }
1456 23
        }
1457
        return $logResult;
1458 23
    }
1459 23
1460 23
    /**
1461 23
     * Save RAW Curl Request & Response to files in Temp directory
1462 23
     */
1463
    public function saveDebugFiles()
1464
    {
1465 23
        $tmpdir   = sys_get_temp_dir();
1466 23
        $fname    = $this->evidence.'-'.$this->curlInfo['when'].'.'.$this->format;
1467
        $reqname  = $tmpdir.'/request-'.$fname;
1468
        $respname = $tmpdir.'/response-'.$fname;
1469 23
        file_put_contents($reqname, $this->postFields);
1470
        file_put_contents($respname, $this->lastCurlResponse);
1471 23
    }
1472 23
1473
    /**
1474 23
     * Připraví data pro odeslání do FlexiBee
1475
     *
1476
     * @param string $data
1477 23
     */
1478 23
    public function setPostFields($data)
1479
    {
1480
        $this->postFields = $data;
1481
    }
1482
1483
    /**
1484
     * Generuje fragment url pro filtrování.
1485
     *
1486
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
1487
     *
1488
     * @param array  $data
1489 65
     * @param string $joiner default and/or
1490
     * @param string $defop  default operator
1491 65
     *
1492 65
     * @return string
1493
     */
1494
    public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq')
1495 65
    {
1496 65
        $parts = [];
1497
1498
        foreach ($data as $column => $value) {
1499
            if (!is_numeric($column)) {
1500
                if (is_integer($data[$column]) || is_float($data[$column])) {
1501 65
                    $parts[$column] = $column.' eq \''.$data[$column].'\'';
1502
                } elseif (is_bool($data[$column])) {
1503
                    $parts[$column] = $data[$column] ? $column.' eq true' : $column.' eq false';
1504
                } elseif (is_null($data[$column])) {
1505
                    $parts[$column] = $column." is null";
1506
                } else {
1507
                    switch ($value) {
1508
                        case '!null':
1509
                            $parts[$column] = $column." is not null";
1510
                            break;
1511 71
                        case 'is empty':
1512
                        case 'is not empty':
1513 71
                            $parts[$column] = $column.' '.$value;
1514
                            break;
1515
                        default:
1516
                            if ($column == 'stitky') {
1517
                                $parts[$column] = $column."='".self::code($data[$column])."'";
1518
                            } else {
1519
                                $parts[$column] = $column." $defop '".$data[$column]."'";
1520
                            }
1521
                            break;
1522 23
                    }
1523
                }
1524 23
            } else {
1525
                $parts[] = $value;
1526
            }
1527
        }
1528
        return implode(' '.$joiner.' ', $parts);
1529
    }
1530
1531
    /**
1532 15
     * Obtain record/object numeric identificator id:
1533
     * Vrací číselný identifikátor objektu id:
1534 15
     *
1535 15
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1536 15
     *
1537 15
     * @return null|int indentifikátor záznamu reprezentovaného objektem
1538 15
     */
1539 9
    public function getRecordID()
1540 9
    {
1541 15
        $id = $this->getDataValue('id');
1542
        return is_null($id) ? null : intval($id);
1543
    }
1544
1545
    /**
1546
     * Obtain record/object identificator code:
1547
     * Vrací identifikátor objektu code:
1548
     *
1549
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1550 23
     *
1551
     * @return string record code identifier
1552 23
     */
1553 23
    public function getRecordCode()
1554 23
    {
1555 23
        return empty($this->getDataValue('kod')) ? null : self::code($this->getDataValue('kod'));
1556 23
    }
1557 23
1558 23
    /**
1559 23
     * Obtain record/object identificator extId: code: or id:
1560 23
     * Vrací identifikátor objektu extId: code: nebo id:
1561 23
     *
1562 23
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1563 23
     *
1564 23
     * @return string|int|null record code identifier
1565 23
     */
1566
    public function getRecordIdent()
1567 23
    {
1568
        $ident = $this->getExternalID();
1569
        if (empty($ident)) {
1570
            $ident = $this->getRecordCode();
1571
        }
1572
        if (empty($ident)) {
1573
            $ident = $this->getRecordID();
1574
        }
1575
        return $ident;
1576
    }
1577 22
1578
    /**
1579 22
     * Obtain record/object identificator code: or id:
1580
     * Vrací identifikátor objektu code: nebo id:
1581 21
     *
1582
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1583
     * @return string indentifikátor záznamu reprezentovaného objektem
1584
     */
1585
    public function __toString()
1586
    {
1587
        return strval($this->getRecordIdent());
1588
    }
1589 22
1590
    /**
1591 22
     * Gives you FlexiPeeHP class name for Given Evidence
1592 22
     *
1593 22
     * @param string $evidence
1594
     * @return string Class name
1595
     */
1596 22
    public static function evidenceToClassName($evidence)
1597
    {
1598
        return str_replace(' ', '', ucwords(str_replace('-', ' ', $evidence)));
1599
    }
1600
1601
    /**
1602
     * Obtain ID of first record in evidence
1603
     *
1604
     * @return string|null id or null if no records
1605 22
     */
1606
    public function getFirstRecordID()
1607 22
    {
1608 22
        $firstID    = null;
1609 22
        $keyColumn  = $this->getmyKeyColumn();
1610 22
        $firstIdRaw = $this->getColumnsFromFlexibee([$keyColumn],
1611 22
            ['limit' => 1, 'order' => $keyColumn], $keyColumn);
1612 22
        if (count($firstIdRaw)) {
1613 22
            $firstID = current($firstIdRaw)[$keyColumn];
1614 22
        }
1615 22
        return is_numeric($firstID) ? intval($firstID) : $firstID;
1616 22
    }
1617 22
1618 22
    /**
1619
     * Vrací hodnotu daného externího ID
1620 22
     *
1621
     * @param string $want Which ? If empty,you obtain the first one.
1622
     * @return string
1623
     */
1624
    public function getExternalID($want = null)
1625
    {
1626
        $extid = null;
1627
        $ids   = $this->getDataValue('external-ids');
1628
        if (is_null($want)) {
1629
            if (count($ids)) {
1630
                $extid = current($ids);
1631
            }
1632 22
        } else {
1633
            if (!is_null($ids) && is_array($ids)) {
1634
                foreach ($ids as $id) {
1635
                    if (strstr($id, 'ext:'.$want)) {
1636
                        $extid = str_replace('ext:'.$want.':', '', $id);
1637
                    }
1638
                }
1639
            }
1640
        }
1641 23
        return $extid;
1642
    }
1643 23
1644 23
    /**
1645 23
     * Obtain actual GlobalVersion
1646 23
     * Vrací aktuální globální verzi změn
1647 16
     *
1648 16
     * @link https://www.flexibee.eu/api/dokumentace/ref/changes-api#globalVersion Globální Verze
1649 23
     * @return type
1650
     */
1651
    public function getGlobalVersion()
1652
    {
1653
        $this->getFlexiData(null, ['add-global-version' => 'true', 'limit' => 1]);
1654
1655
        return $this->globalVersion;
1656
    }
1657
1658 23
    /**
1659
     * Obtain content type of last response
1660 23
     *
1661 23
     * @return string
1662 23
     */
1663 23
    public function getResponseFormat()
1664 23
    {
1665 23
        if (isset($this->curlInfo['content_type'])) {
1666 23
            $responseFormat = $this->curlInfo['content_type'];
1667 23
        } else {
1668 23
            $responseFormat = null;
1669
        }
1670
        return $responseFormat;
1671
    }
1672
1673
    /**
1674
     * Return the same response format for one and multiplete results
1675
     *
1676
     * @param array $responseBody
1677 23
     * @return array
1678
     */
1679 23
    public function unifyResponseFormat($responseBody)
1680 23
    {
1681 23
        if (!is_array($responseBody) || array_key_exists('message',
1682 23
                $responseBody)) { //Unifi response format
1683 23
            $response = $responseBody;
1684 23
        } else {
1685 13
            $evidence = $this->getResponseEvidence();
1686 13
            if (array_key_exists($evidence, $responseBody)) {
1687 23
                $response        = [];
1688
                $evidenceContent = $responseBody[$evidence];
1689
                if (array_key_exists(0, $evidenceContent)) {
1690
                    $response[$evidence] = $evidenceContent; //Multiplete Results
1691
                } else {
1692
                    $response[$evidence][0] = $evidenceContent; //One result
1693
                }
1694
            } else {
1695
                if (isset($responseBody['priloha'])) {
1696 23
                    $response = $responseBody['priloha'];
1697
                } else {
1698 23
                    if (array_key_exists('results', $responseBody)) {
1699 23
                        $response = $responseBody['results'];
1700 23
                    } else {
1701 23
                        $response = $responseBody;
1702 23
                    }
1703 16
                }
1704 16
            }
1705 23
        }
1706
        return $response;
1707
    }
1708
1709
    /**
1710
     * Obtain structure for current (or given) evidence
1711
     *
1712
     * @param string $evidence
1713
     * @return array Evidence structure
1714 23
     */
1715
    public function getColumnsInfo($evidence = null)
1716 23
    {
1717 23
        $columnsInfo = null;
1718 23
        $infoSource  = self::$infoDir.'/Properties.'.(empty($evidence) ? $this->getEvidence()
1719 23
                : $evidence).'.json';
1720 23
        if (file_exists($infoSource)) {
1721 16
            $columnsInfo = json_decode(file_get_contents($infoSource), true);
1722 16
        }
1723 23
        return $columnsInfo;
1724
    }
1725
1726
    /**
1727
     * Gives you properties for (current) evidence column
1728
     * 
1729
     * @param string $column    name of column
1730
     * @param string $evidence  evidence name if different
1731 23
     * 
1732
     * @return array column properties or null if column not exits
1733 23
     */
1734 1
    public function getColumnInfo($column, $evidence = null)
1735 1
    {
1736 23
        $columnsInfo = $this->getColumnsInfo(empty($evidence) ? $this->getEvidence()
1737 23
                : $evidence);
1738
        return array_key_exists($column, $columnsInfo) ? $columnsInfo[$column] : null;
1739
    }
1740
1741
    /**
1742
     * Obtain actions for current (or given) evidence
1743
     *
1744 20
     * @param string $evidence
1745
     * @return array Evidence structure
1746 20
     */
1747 20
    public function getActionsInfo($evidence = null)
1748 20
    {
1749 20
        $actionsInfo = null;
1750
        if (is_null($evidence)) {
1751
            $evidence = $this->getEvidence();
1752
        }
1753
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1754
        if (isset(\FlexiPeeHP\Actions::$$propsName)) {
1755 20
            $actionsInfo = Actions::$$propsName;
1756
        }
1757
        return $actionsInfo;
1758
    }
1759
1760
    /**
1761
     * Obtain relations for current (or given) evidence
1762
     *
1763
     * @param string $evidence
1764
     * @return array Evidence structure
1765
     */
1766
    public function getRelationsInfo($evidence = null)
1767
    {
1768
        $relationsInfo = null;
1769
        if (is_null($evidence)) {
1770
            $evidence = $this->getEvidence();
1771
        }
1772
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1773
        if (isset(\FlexiPeeHP\Relations::$$propsName)) {
1774
            $relationsInfo = Relations::$$propsName;
1775
        }
1776
        return $relationsInfo;
1777
    }
1778
1779
    /**
1780
     * Obtain info for current (or given) evidence
1781
     *
1782
     * @param string $evidence
1783
     * @return array Evidence info
1784
     */
1785 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...
1786
    {
1787
        $evidencesInfo = null;
1788
        if (is_null($evidence)) {
1789
            $evidence = $this->getEvidence();
1790
        }
1791
        if (isset(EvidenceList::$evidences[$evidence])) {
1792
            $evidencesInfo = EvidenceList::$evidences[$evidence];
1793
        }
1794
        return $evidencesInfo;
1795
    }
1796
1797
    /**
1798
     * Obtain name for current (or given) evidence path
1799
     *
1800
     * @param string $evidence Evidence Path
1801
     * @return array Evidence info
1802
     */
1803 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...
1804
    {
1805
        $evidenceName = null;
1806
        if (is_null($evidence)) {
1807
            $evidence = $this->getEvidence();
1808
        }
1809
        if (isset(EvidenceList::$name[$evidence])) {
1810
            $evidenceName = EvidenceList::$name[$evidence];
1811
        }
1812
        return $evidenceName;
1813
    }
1814
1815
    /**
1816
     * Save current object to file
1817
     *
1818
     * @param string $destfile path to file
1819
     */
1820
    public function saveResponseToFile($destfile)
1821
    {
1822
        if (strlen($this->lastCurlResponse)) {
1823
            $this->doCurlRequest($this->apiURL, 'GET', $this->format);
1824
        }
1825
        file_put_contents($destfile, $this->lastCurlResponse);
1826
    }
1827
1828
    /**
1829
     * Obtain established relations listing
1830
     *
1831
     * @return array Null or Relations
1832
     */
1833
    public function getVazby($id = null)
1834
    {
1835
        if (is_null($id)) {
1836
            $id = $this->getRecordID();
1837
        }
1838
        if (!empty($id)) {
1839
            $vazbyRaw = $this->getColumnsFromFlexibee(['vazby'],
1840
                ['relations' => 'vazby', 'id' => $id]);
1841
            $vazby    = array_key_exists('vazby', $vazbyRaw[0]) ? $vazbyRaw[0]['vazby']
1842
                    : null;
1843
        } else {
1844
            throw new \Exception(_('ID requied to get record relations '));
1845 23
        }
1846
        return $vazby;
1847 23
    }
1848
1849
    /**
1850
     * Gives You URL for Current Record in FlexiBee web interface
1851
     *
1852
     * @return string url
1853
     */
1854
    public function getFlexiBeeURL()
1855
    {
1856
        $parsed_url = parse_url(str_replace('.'.$this->format, '', $this->apiURL));
1857 23
        $scheme     = isset($parsed_url['scheme']) ? $parsed_url['scheme'].'://'
1858
                : '';
1859 23
        $host       = isset($parsed_url['host']) ? $parsed_url['host'] : '';
1860
        $port       = isset($parsed_url['port']) ? ':'.$parsed_url['port'] : '';
1861
        $user       = isset($parsed_url['user']) ? $parsed_url['user'] : '';
1862
        $pass       = isset($parsed_url['pass']) ? ':'.$parsed_url['pass'] : '';
1863
        $pass       = ($user || $pass) ? "$pass@" : '';
1864
        $path       = isset($parsed_url['path']) ? $parsed_url['path'] : '';
1865
        return $scheme.$user.$pass.$host.$port.$path;
1866
    }
1867
1868
    /**
1869
     * Set Record Key
1870
     *
1871
     * @param int|string $myKeyValue
1872
     * @return boolean
1873
     */
1874
    public function setMyKey($myKeyValue)
1875
    {
1876
        if (substr($myKeyValue, 0, 4) == 'ext:') {
1877
            $extIds = $this->getDataValue('external-ids');
1878
            if (count($extIds)) {
1879
                $extIds = array_combine($extIds, $extIds);
1880
            }
1881
            $extIds[$myKeyValue] = $myKeyValue;
1882
            $res                 = $this->setDataValue('external-ids', $extIds);
1883
        } else {
1884
            $res = parent::setMyKey($myKeyValue);
1885
        }
1886
        $this->updateApiURL();
1887
        return $res;
1888
    }
1889
1890
    /**
1891
     * Set or get ignore not found pages flag
1892
     *
1893
     * @param boolean $ignore set flag to
1894
     *
1895
     * @return boolean get flag state
1896
     */
1897
    public function ignore404($ignore = null)
1898
    {
1899
        if (!is_null($ignore)) {
1900
            $this->ignoreNotFound = $ignore;
1901
        }
1902
        return $this->ignoreNotFound;
1903
    }
1904
1905
    /**
1906
     * Send Document by mail
1907
     *
1908
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
1909
     *
1910
     * @param string $to         Email ecipient
1911
     * @param string $subject    Email Subject
1912
     * @param string $body       Email Text
1913
     *
1914
     * @return int http response code
1915
     */
1916
    public function sendByMail($to, $subject, $body, $cc = null)
1917
    {
1918
        $this->setPostFields($body);
1919
1920
        $this->performRequest(rawurlencode($this->getRecordID()).'/odeslani-dokladu?to='.$to.'&subject='.urlencode($subject).'&cc='.$cc
1921
            , 'PUT', 'xml');
1922
1923
        return $this->lastResponseCode == 200;
1924
    }
1925
1926
    /**
1927
     * Send all unsent Invoices by mail
1928
     *
1929
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
1930
     * @return int http response code
1931
     */
1932
    public function sendUnsent()
1933
    {
1934
        return $this->doCurlRequest('automaticky-odeslat-neodeslane', 'PUT',
1935
                'xml');
1936
    }
1937
1938
    /**
1939
     * FlexiBee date to PHP DateTime conversion
1940
     *
1941
     * @param string $flexidate 2017-05-26+02:00
1942
     *
1943
     * @return \DateTime | false
1944
     */
1945
    public static function flexiDateToDateTime($flexidate)
1946
    {
1947
        return \DateTime::createFromFormat(self::$DateFormat, $flexidate)->setTime(0,
1948
                0);
1949
    }
1950
1951
    /**
1952
     * FlexiBee dateTime to PHP DateTime conversion
1953
     *
1954
     * @param string $flexidatetime 2017-09-26T10:00:53.755+02:00 or older 2017-05-19T00:00:00+02:00
1955
     *
1956
     * @return \DateTime | false
1957
     */
1958
    public static function flexiDateTimeToDateTime($flexidatetime)
1959
    {
1960
        if (strchr($flexidatetime, '.')) { //NewFormat
1961
            $format = self::$DateTimeFormat;
1962
        } else { // Old format
1963
            $format = 'Y-m-d\TH:i:s+P';
1964
        }
1965
        return \DateTime::createFromFormat($format, $flexidatetime);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression \DateTime::createFromFor...ormat, $flexidatetime); of type DateTime|false adds false to the return on line 1965 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...
1966
    }
1967
1968
    /**
1969
     * Získá dokument v daném formátu
1970
     * Obtain document in given format
1971
     *
1972
     * @param string $format  pdf/csv/xml/json/ ...
1973
     * @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...
1974
     *
1975
     * @return string|null filename downloaded or none
1976
     */
1977
    public function getInFormat($format)
1978
    {
1979
        $response = null;
1980
        if ($this->setFormat($format)) {
1981
            $urlParams = [];
1982
            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...
1983
                $urlParams['report-name'] = $reportName;
1984
            }
1985
            if ($format == 'html') {
1986
                $urlParams['inDesktopApp'] = 'true';
1987
            }
1988
            if (($this->doCurlRequest($this->addUrlParams($this->apiURL,
1989
                        $urlParams), 'GET') == 200)) {
1990
                $response = $this->lastCurlResponse;
1991
            }
1992
        }
1993
        return $response;
1994
    }
1995
1996
    /**
1997
     * Uloží dokument v daném formátu do složky v systému souborů
1998
     * Save document in given format to directory in filesystem
1999
     *
2000
     * @param string $format  pdf/csv/xml/json/ ...
2001
     * @param string $destDir where to put file (prefix)
2002
     * @param string $reportName Template used to generate PDF
2003
     *
2004
     * @return string|null filename downloaded or none
2005
     */
2006
    public function downloadInFormat($format, $destDir = './',
2007
                                     $reportName = null)
2008
    {
2009
        $fileOnDisk   = null;
2010
        $formatBackup = $this->format;
2011
        if ($this->setFormat($format)) {
2012
            $downloadTo = $destDir.$this->getEvidence().'_'.$this->getMyKey().'.'.$format;
2013
            if (($this->doCurlRequest(empty($reportName) ? $this->apiURL : $this->addUrlParams($this->apiURL,
2014
                            ['report-name' => $reportName]), 'GET') == 200) && (file_put_contents($downloadTo,
2015
                    $this->lastCurlResponse) !== false)) {
2016
                $fileOnDisk = $downloadTo;
2017
            }
2018
            $this->setFormat($formatBackup);
2019
        }
2020
        return $fileOnDisk;
2021
    }
2022
2023
    /**
2024
     * Compile and send Report about Error500 to FlexiBee developers
2025
     * If FlexiBee is running on localost try also include java backtrace
2026
     *
2027
     * @param array $errorResponse result of parseError();
2028
     */
2029
    public function error500Reporter($errorResponse)
2030
    {
2031
        $ur = str_replace('/c/'.$this->company, '',
2032
            str_replace($this->url, '', $this->curlInfo['url']));
2033
        if (!array_key_exists($ur, $this->reports)) {
2034
            $tmpdir   = sys_get_temp_dir();
2035 23
            $myTime   = $this->curlInfo['when'];
2036
            $curlname = $tmpdir.'/curl-'.$this->evidence.'-'.$myTime.'.json';
2037 23
            file_put_contents($curlname,
2038 23
                json_encode($this->curlInfo, JSON_PRETTY_PRINT));
2039 23
2040 23
            $report = new \Ease\Mailer($this->reportRecipient,
2041
                'Error report 500 - '.$ur);
2042
2043
            $d     = dir($tmpdir);
2044
            while (false !== ($entry = $d->read())) {
2045
                if (strstr($entry, $myTime)) {
2046
                    $ext  = pathinfo($tmpdir.'/'.$entry, PATHINFO_EXTENSION);
2047
                    $mime = Formats::suffixToContentType($ext);
2048
                    $report->addFile($tmpdir.'/'.$entry,
2049
                        empty($mime) ? 'text/plain' : $mime);
2050
                }
2051
            }
2052
            $d->close();
2053
2054
            if ((strstr($this->url, '://localhost') || strstr($this->url,
2055
                    '://127.')) && file_exists('/var/log/flexibee.log')) {
2056
2057
                $fl = fopen("/var/log/flexibee.log", "r");
2058
                if ($fl) {
2059
                    $tracelog = [];
2060
                    for ($x_pos = 0, $ln = 0, $output = array(); fseek($fl,
2061
                            $x_pos, SEEK_END) !== -1; $x_pos--) {
2062
                        $char = fgetc($fl);
2063
                        if ($char === "\n") {
2064
                            $tracelog[] = $output[$ln];
2065
                            if (strstr($output[$ln], $errorResponse['message'])) {
2066
                                break;
2067
                            }
2068
                            $ln++;
2069
                            continue;
2070
                        }
2071
                        $output[$ln] = $char.((array_key_exists($ln, $output)) ? $output[$ln]
2072
                                : '');
2073
                    }
2074
2075
                    $trace     = implode("\n", array_reverse($tracelog));
2076
                    $tracefile = $tmpdir.'/trace-'.$this->evidence.'-'.$myTime.'.log';
2077
                    file_put_contents($tracefile, $trace);
2078
                    $report->addItem("\n\n".$trace);
2079
                    fclose($fl);
2080
                }
2081
            } else {
2082
                $report->addItem($errorResponse['message']);
2083
            }
2084
2085
            $licenseInfo = $this->performRequest($this->url.'/default-license.json');
2086
2087
            $report->addItem("\n\n".json_encode($licenseInfo['license'],
2088
                    JSON_PRETTY_PRINT));
2089
2090
            if ($report->send()) {
2091
                $this->reports[$ur] = $myTime;
2092
            }
2093
        }
2094
    }
2095
2096
    /**
2097
     * Returns code:CODE
2098
     *
2099
     * @param string $code
2100
     *
2101
     * @return string
2102
     */
2103
    public static function code($code)
2104
    {
2105
        return 'code:'.self::uncode($code);
2106
    }
2107
2108
    /**
2109
     * Returns CODE without code: prefix
2110
     *
2111
     * @param string $code
2112
     *
2113
     * @return string
2114
     */
2115
    public static function uncode($code)
2116
    {
2117
        return str_replace(['code:', 'code%3A'], '', $code);
2118
    }
2119
2120
    /**
2121
     * Remove all @ items from array
2122
     *
2123
     * @param array $data original data
2124
     *
2125
     * @return array data without @ columns
2126
     */
2127
    public static function arrayCleanUP($data)
2128
    {
2129
        return array_filter(
2130
            $data,
2131
            function ($key) {
2132
            return !strchr($key, '@');
2133
        }, ARRAY_FILTER_USE_KEY);
2134
    }
2135
2136
    /**
2137
     * Add Info about used user, server and libraries
2138
     *
2139
     * @param string $additions Additional note text
2140
     */
2141
    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...
2142
    {
2143
        $this->addStatusMessage('FlexiBee '.str_replace('://',
2144
                '://'.$this->user.'@', str_replace('.json', '', $this->apiURL)).' FlexiPeeHP v'.self::$libVersion.' (FlexiBee '.EvidenceList::$version.') EasePHP Framework v'.\Ease\Atom::$frameworkVersion.' '.$additions,
2145
            'debug');
2146
    }
2147
2148
    /**
2149
     * Reconnect After unserialization
2150
     */
2151
    public function __wakeup()
2152
    {
2153
        parent::__wakeup();
2154
        $this->curlInit();
2155
    }
2156
}
2157