Test Failed
Pull Request — master (#6)
by Vítězslav
03:51
created

FlexiBeeRO::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1429
                    $kod = \Ease\Sand::rip($data[$this->keyColumn]);
0 ignored issues
show
Bug introduced by
The property keyColumn does not seem to exist. Did you mean fbKeyColumn?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

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