Completed
Push — master ( d5d70a...ca076d )
by Vítězslav
09:56
created

FlexiBeeRO::setPostFields()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
rs 10
1
<?php
2
/**
3
 * FlexiPeeHP - Třída pro čtení z FlexiBee.
4
 *
5
 * @author     Vítězslav Dvořák <[email protected]>
6
 * @copyright  (C) 2015,2016 Spoje.Net
7
 */
8
9
namespace FlexiPeeHP;
10
11
class FlexiBeeRO extends \Ease\Brick
12
{
13
    /**
14
     * Základní namespace pro komunikaci s FlexiBEE.
15
     *
16
     * @var string Jmený prostor datového bloku odpovědi
17
     */
18
    public $nameSpace = 'winstrom';
19
20
    /**
21
     * Datový blok v poli odpovědi.
22
     *
23
     * @var string
24
     */
25
    public $resultField = 'results';
26
27
    /**
28
     * Verze protokolu použitého pro komunikaci.
29
     *
30
     * @var string Verze použitého API
31
     */
32
    public $protoVersion = '1.0';
33
34
    /**
35
     * Evidence užitá objektem.
36
     *
37
     * @link https://demo.flexibee.eu/c/demo/evidence-list Přehled evidencí
38
     * @var string
39
     */
40
    public $evidence = null;
41
42
    /**
43
     * Výchozí formát pro komunikaci.
44
     *
45
     * @link https://www.flexibee.eu/api/dokumentace/ref/format-types Přehled možných formátů
46
     *
47
     * @var string json|xml|...
48
     */
49
    public $format = 'json';
50
51
    /**
52
     * Curl Handle.
53
     *
54
     * @var resource
55
     */
56
    public $curl = null;
57
58
    /**
59
     * @link https://demo.flexibee.eu/devdoc/company-identifier Identifikátor firmy
60
     * @var string
61
     */
62
    public $company = null;
63
64
    /**
65
     * Server[:port]
66
     * @var string
67
     */
68
    public $url = null;
69
70
    /**
71
     * REST API Username
72
     * @var string
73
     */
74
    public $user = null;
75
76
    /**
77
     * REST API Password
78
     * @var string
79
     */
80
    public $password = null;
81
82
    /**
83
     * @var array Pole HTTP hlaviček odesílaných s každým požadavkem
84
     */
85
    public $defaultHttpHeaders = ['User-Agent' => 'FlexiPeeHP'];
86
87
    /**
88
     * Default additional request url parameters after question mark
89
     * 
90
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls   Common params
91
     * @link https://www.flexibee.eu/api/dokumentace/ref/paging Paging params
92
     * @var array
93
     */
94
    public $defaultUrlParams = ['limit' => 0];
95
96
    /**
97
     * Identifikační řetězec.
98
     *
99
     * @var string
100
     */
101
    public $init = null;
102
103
    /**
104
     * Sloupeček s názvem.
105
     *
106
     * @var string
107
     */
108
    public $nameColumn = 'nazev';
109
110
    /**
111
     * Sloupeček obsahující datum vložení záznamu do shopu.
112
     *
113
     * @var string
114
     */
115
    public $myCreateColumn = 'false';
116
117
    /**
118
     * Slopecek obsahujici datum poslení modifikace záznamu do shopu.
119
     *
120
     * @var string
121
     */
122
    public $myLastModifiedColumn = 'lastUpdate';
123
124
    /**
125
     * Klíčový idendifikátor záznamu.
126
     *
127
     * @var string
128
     */
129
    public $fbKeyColumn = 'id';
130
131
    /**
132
     * Informace o posledním HTTP requestu.
133
     *
134
     * @var *
135
     */
136
    public $info;
137
138
    /**
139
     * Informace o poslední HTTP chybě.
140
     *
141
     * @var string
142
     */
143
    public $lastCurlError = null;
144
145
    /**
146
     * Used codes storage.
147
     *
148
     * @var array
149
     */
150
    public $codes = null;
151
152
    /**
153
     * Last Inserted ID.
154
     *
155
     * @var int
156
     */
157
    public $lastInsertedID = null;
158
159
    /**
160
     * Default Line Prefix.
161
     *
162
     * @var string
163
     */
164
    public $prefix = '/c/';
165
166
    /**
167
     * Raw Content of last curl response
168
     * 
169
     * @var string
170
     */
171
    public $lastCurlResponse;
172
173
    /**
174
     * HTTP Response code of last request
175
     *
176
     * @var int
177
     */
178
    public $lastResponseCode = null;
179
180
    /**
181
     * Array of fields for next curl POST operation
182
     *
183
     * @var array
184
     */
185
    protected $postFields = [];
186
187
    /**
188
     * Last operation result data or message(s)
189
     *
190
     * @var array
191
     */
192
    public $lastResult = null;
193
194
    /**
195
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
196
     * @var string
197
     */
198
    protected $action;
199
200
    /**
201
     * Pole akcí které podporuje ta která evidence
202
     * @link https://demo.flexibee.eu/c/demo/faktura-vydana/actions.json Např. Akce faktury
203
     * @var array
204
     */
205
    public $actionsAvailable = null;
206
207
    /**
208
     * Třída pro práci s FlexiBee.
209
     *
210
     * @param mixed $init výchozí selektor dat
211
     */
212
    public function __construct($init = null)
213
    {
214
        $this->init = $init;
215
216
        parent::__construct();
217
        $this->setUp();
218
        $this->curlInit();
219
        if ($init) {
220
            $this->processInit($init);
221
        }
222
    }
223
224
    /**
225
     * SetUp Object to be ready for connect
226
     */
227
    public function setUp()
228
    {
229
        if (is_null($this->company) && defined('FLEXIBEE_COMPANY')) {
230
            $this->company = constant('FLEXIBEE_COMPANY');
231
        }
232
        if (is_null($this->url) && defined('FLEXIBEE_URL')) {
233
            $this->url = constant('FLEXIBEE_URL');
234
        }
235
236
        if (is_null($this->user) && defined('FLEXIBEE_LOGIN')) {
237
            $this->user = constant('FLEXIBEE_LOGIN');
238
        }
239
240
        if (is_null($this->password) && defined('FLEXIBEE_PASSWORD')) {
241
            $this->password = constant('FLEXIBEE_PASSWORD');
242
        }
243
    }
244
245
    /**
246
     * Inicializace CURL
247
     */
248
    public function curlInit()
249
    {
250
        $this->curl = \curl_init(); // create curl resource
251
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); // return content as a string from curl_exec
252
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true); // follow redirects (compatibility for future changes in FlexiBee)
253
        curl_setopt($this->curl, CURLOPT_HTTPAUTH, true);       // HTTP authentication
254
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); // FlexiBee by default uses Self-Signed certificates
255
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
256
        curl_setopt($this->curl, CURLOPT_VERBOSE, true); // For debugging
257
        curl_setopt($this->curl, CURLOPT_USERPWD,
258
            $this->user.':'.$this->password); // set username and password
259
    }
260
261
    /**
262
     * Zinicializuje objekt dle daných dat
263
     * 
264
     * @param mixed $init
265
     */
266
    public function processInit($init)
267
    {
268
        if (is_integer($init)) {
269
            $this->loadFromFlexiBee($init);
270
        } elseif (is_array($init)) {
271
            $this->takeData($init);
272
        }
273
    }
274
275
    /**
276
     * Nastaví Evidenci pro Komunikaci.
277
     *
278
     * @param string $evidence
279
     */
280
    public function setEvidence($evidence)
281
    {
282
        $this->evidence = $evidence;
283
    }
284
285
    /**
286
     * Vrací právě používanou evidenci pro komunikaci
287
     * 
288
     * @return string
289
     */
290
    public function getEvidence()
291
    {
292
        return $this->evidence;
293
    }
294
295
    /**
296
     * Převede rekurzivně Objekt na pole.
297
     *
298
     * @param object|array $object
299
     *
300
     * @return array
301
     */
302
    public static function object2array($object)
303
    {
304
        $result = null;
305
        if (is_object($object)) {
306
            $objectData = get_object_vars($object);
307
            if (is_array($objectData) && count($objectData)) {
308
                $result = array_map('self::object2array', $objectData);
309
            }
310 View Code Duplication
        } else {
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...
311
            if (is_array($object)) {
312
                foreach ($object as $item => $value) {
313
                    $result[$item] = self::object2array($value);
314
                }
315
            } else {
316
                $result = $object;
317
            }
318
        }
319
320
        return $result;
321
    }
322
323
    /**
324
     * Převede rekurzivně v poli všechny objekty na jejich identifikátory.
325
     *
326
     * @param object|array $object
327
     *
328
     * @return array
329
     */
330
    public static function objectToID($object)
331
    {
332
        $result = null;
333
        if (is_object($object)) {
334
            $result = $object->__toString();
335 View Code Duplication
        } else {
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...
336
            if (is_array($object)) {
337
                foreach ($object as $item => $value) {
338
                    $result[$item] = self::objectToID($value);
339
                }
340
            } else { //String
341
                $result = $object;
342
            }
343
        }
344
345
        return $result;
346
    }
347
348
    /**
349
     * Funkce, která provede I/O operaci a vyhodnotí výsledek.
350
     *
351
     * @param string $urlSuffix část URL za identifikátorem firmy.
352
     * @param string $method    HTTP/REST metoda
353
     * @param string $format    Requested format
354
     * @return array|boolean Výsledek operace
355
     */
356
    public function performRequest($urlSuffix = null, $method = 'GET',
357
                                   $format = null)
358
    {
359
        if (is_null($format)) {
360
            $format = $this->format;
361
        }
362
        if (is_null($urlSuffix)) {
363
            $urlSuffix = $this->evidence.'.'.$format;
364
        }
365
        $url = $this->url.$this->prefix.$this->company.'/'.$urlSuffix;
366
367
        $this->doCurlRequest($url, $method, $format);
0 ignored issues
show
Documentation introduced by
$method is of type string, but the function expects a object<FlexiPeeHP\strinf>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
368
369
        if ($this->lastResponseCode != 200 && $this->lastResponseCode != 201) {
370
            $this->lastCurlError = curl_error($this->curl);
371
            switch ($format) {
372
                case 'json':
373
                    $response = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/',
374
                        function ($match) {
375
                        return mb_convert_encoding(pack('H*', $match[1]),
376
                            'UTF-8', 'UCS-2BE');
377
                    }, $this->lastCurlResponse);
378
                    $response = (json_encode(json_decode($response, true, 10),
379
                            JSON_PRETTY_PRINT));
380
                    break;
381
                case 'xml':
382
                    if (strlen($this->lastCurlResponse)) {
383
                        $response = self::xml2array($this->lastCurlResponse);
384
                    }
385
                    break;
386
            }
387
388
            if (is_array($response)) {
389
                $result = urldecode(http_build_query($response));
0 ignored issues
show
Bug introduced by
The variable $response does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
390
            } elseif (strlen($response) && ($response != 'null')) {
391
                $result = urldecode(http_build_query(self::object2array(current(json_decode($response)))));
392
            } else {
393
                $result = null;
394
            }
395
396
            if ($response == 'null') {
397
                if ($this->lastResponseCode == 200) {
398
                    $response = true;
399
                } else {
400
                    $response = null;
401
                }
402
            } else {
403
                if (is_string($response)) {
404
                    $response = self::object2array(current(json_decode($response)));
405
                }
406
            }
407
408
            if (is_array($response) && ($this->lastResponseCode == 400)) {
409
                $this->logResult($response);
410
            } else {
411
                $this->addStatusMessage(sprintf('Error (HTTP %d): <pre>%s</pre> %s',
412
                        curl_getinfo($this->curl, CURLINFO_HTTP_CODE), $result,
413
                        $this->lastCurlError), 'error');
414
                $this->addStatusMessage($url, 'info');
415
                if (count($this->postFields)) {
416
                    $this->addStatusMessage(urldecode(http_build_query($this->postFields)),
417
                        'debug');
418
                }
419
            }
420
            return $response;
421
        }
422
        // Parse response
423
        $responseDecoded = [];
424
        switch ($format) {
425
            case 'json':
426
                $responseDecoded = json_decode($this->lastCurlResponse, true, 10);
427
                if (($method == 'PUT') && isset($responseDecoded[$this->nameSpace][$this->resultField][0]['id'])) {
428
                    $this->lastInsertedID = $responseDecoded[$this->nameSpace][$this->resultField][0]['id'];
429
                } else {
430
                    $this->lastInsertedID = null;
431
                }
432
                $decodeError = json_last_error_msg();
433
                if ($decodeError != 'No error') {
434
                    $this->addStatusMessage($decodeError, 'error');
435
                }
436
                break;
437
            case 'xml':
438
                if (strlen($this->lastCurlResponse)) {
439
                    $responseDecoded = self::xml2array($this->lastCurlResponse);
440
                } else {
441
                    $responseDecoded = null;
442
                }
443
                break;
444
        }
445
446
        // Get response body root automatically
447
        if (isset($responseDecoded[$this->nameSpace])) {
448
            $responseDecoded = $responseDecoded[$this->nameSpace];
449
        }
450
451
        $this->lastResult = $responseDecoded;
0 ignored issues
show
Documentation Bug introduced by
It seems like $responseDecoded of type * is incompatible with the declared type array of property $lastResult.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
452
        return $responseDecoded;
453
    }
454
455
    /**
456
     * Vykonej HTTP požadavek
457
     *
458
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
459
     * @param string $url URL požadavku
460
     * @param strinf $method HTTP Method GET|POST|PUT|OPTIONS|DELETE
461
     * @param string $format
462
     */
463
    public function doCurlRequest($url, $method, $format)
464
    {
465
        curl_setopt($this->curl, CURLOPT_URL, $url);
466
// Nastavení samotné operace
467
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
468
//Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411
469
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
470
471
        $httpHeaders = $this->defaultHttpHeaders;
472
        switch ($format) {
473
            case 'json':
474
                $httpHeaders['Accept']       = 'application/json';
475
                $httpHeaders['Content-Type'] = 'application/json';
476
477
                break;
478
            case 'xml':
479
                $httpHeaders['Accept']       = 'application/xml';
480
                $httpHeaders['Content-Type'] = 'application/xml';
481
                break;
482
        }
483
484
        $httpHeadersFinal = [];
485
        foreach ($httpHeaders as $key => $value) {
486
            $httpHeadersFinal[] = $key.': '.$value;
487
        }
488
489
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
490
491
// Proveď samotnou operaci
492
        $this->lastCurlResponse = curl_exec($this->curl);
493
494
        $this->info = curl_getinfo($this->curl);
495
496
        $this->lastResponseCode = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
497
    }
498
499
    /**
500
     * Todo: Sem vyčlenit zpracování výsledku requestu
501
     */
502
    public function processRequest()
503
    {
504
505
    }
506
507
    /**
508
     * Nastaví druh prováděné akce.
509
     *
510
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
511
     * @param string $action
512
     * @return boolean
513
     */
514
    public function setAction($action)
515
    {
516
        $result = false;
517
        if (is_null($this->actionsAvailable)) {
518
            $this->action = $action;
519
            $result       = true;
520
        } else {
521
            if (array_search($action, $this->actionsAvailable)) {
522
                $this->action = $action;
523
                $result       = true;
524
            }
525
        }
526
        return $result;
527
    }
528
529
    /**
530
     * Convert XML to array.
531
     *
532
     * @param string $xml
533
     *
534
     * @return array
535
     */
536
    public static function xml2array($xml)
537
    {
538
        $arr = [];
539
540
        if (is_string($xml)) {
541
            $xml = simplexml_load_string($xml);
542
        }
543
544
        foreach ($xml->children() as $r) {
545
            if (count($r->children()) == 0) {
546
                $arr[$r->getName()] = strval($r);
547
            } else {
548
                $arr[$r->getName()][] = self::xml2array($r);
549
            }
550
        }
551
552
        return $arr;
553
    }
554
555
    /**
556
     * Odpojení od FlexiBee.
557
     */
558
    public function disconnect()
559
    {
560
        if (is_resource($this->curl)) {
561
            curl_close($this->curl);
562
        }
563
        $this->curl = null;
564
    }
565
566
    public function __destruct()
567
    {
568
        $this->disconnect();
569
    }
570
571
    /**
572
     * Načte data z FlexiBee.
573
     *
574
     * @param string $suffix dotaz
575
     */
576
    public function loadFlexiData($suffix = null)
577
    {
578
        return $this->takeData($this->getFlexiData($suffix));
579
    }
580
581
    /**
582
     * Načte řádek dat z FlexiBee.
583
     *
584
     * @param int $recordID id požadovaného záznamu
585
     *
586
     * @return array
587
     */
588
    public function getFlexiRow($recordID)
589
    {
590
        $record   = null;
591
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
592
        if (isset($response[$this->evidence])) {
593
            $record = $response[$this->evidence][0];
594
        }
595
596
        return $record;
597
    }
598
599
    /**
600
     * Načte data z FlexiBee.
601
     *
602
     * @param string $suffix     dotaz
603
     * @param string|array $conditions Volitelný filtrovací výraz
604
     */
605
    public function getFlexiData($suffix = null, $conditions = null)
606
    {
607
        $urlParams = $this->defaultUrlParams;
608
        if (!is_null($conditions)) {
609
            if (is_array($conditions)) {
610
611
                if (isset($conditions['detail'])) {
612
                    \Ease\Sand::divDataArray($conditions, $urlParams, 'detail');
613
                }
614
                if (isset($conditions['sort'])) {
615
                    \Ease\Sand::divDataArray($conditions, $urlParams, 'sort');
616
                }
617
                if (isset($conditions['order'])) {
618
                    \Ease\Sand::divDataArray($conditions, $urlParams, 'order');
619
                }
620
                if (isset($conditions['limit'])) {
621
                    \Ease\Sand::divDataArray($conditions, $urlParams, 'limit');
622
                }
623
                if (isset($conditions['start'])) {
624
                    \Ease\Sand::divDataArray($conditions, $urlParams, 'start');
625
                }
626
                if (isset($conditions['add-row-count'])) {
627
                    \Ease\Sand::divDataArray($conditions, $urlParams,
628
                        'add-row-count');
629
                }
630
631
                $conditions = $this->flexiUrl($conditions);
632
            }
633
634
            if (strlen($conditions) && ($conditions[0] != '/')) {
635
                $conditions = '/'.rawurlencode('('.($conditions).')');
636
            }
637
        } else {
638
            $conditions = '';
639
        }
640
        if (strlen($suffix)) {
641
            $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.$suffix.'&'.http_build_query($urlParams),
642
                'GET');
643
        } else {
644
            $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.http_build_query($urlParams),
645
                'GET');
646
        }
647
        if (isset($transactions[$this->evidence])) {
648
            $result = $transactions[$this->evidence];
649
        } else {
650
            $result = $transactions;
651
        }
652
653
        return $result;
654
    }
655
656
    /**
657
     * Načte záznam z FlexiBee.
658
     *
659
     * @param int $id ID záznamu
660
     *
661
     * @return int počet načtených položek
662
     */
663 View Code Duplication
    public function loadFromFlexiBee($id = 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...
664
    {
665
        $data = [];
666
        if (is_null($id)) {
667
            $id = $this->getMyKey();
668
        }
669
670
        $flexidata = $this->getFlexiData(null, '/'.$id);
671
        if (count($flexidata) == 1) {
672
            $data = current($flexidata);
673
        }
674
        return $this->takeData($data);
675
    }
676
677
    /**
678
     * Převede data do Json formátu pro FlexiBee.
679
     *
680
     * @param array $data
681
     *
682
     * @return string
683
     */
684
    public function jsonizeData($data)
685
    {
686
        $jsonize = [
687
            $this->nameSpace => [
688
                '@version' => $this->protoVersion,
689
                $this->evidence => $this->objectToID($data),
690
            ],
691
        ];
692
693
        if (!is_null($this->action)) {
694
            $jsonize[$this->nameSpace][$this->evidence.'@action'] = $this->action;
695
            $this->action                                         = null;
696
        }
697
698
        return json_encode($jsonize);
699
    }
700
701
    /**
702
     * Test if given record ID exists in FlexiBee.
703
     *
704
     * @param string|int $identifer
705
     */
706
    public function idExists($identifer = null)
707
    {
708
        if (is_null($identifer)) {
709
            $identifer = $this->getMyKey();
710
        }
711
        $flexiData = $this->getFlexiData(
712
            'detail=custom:'.$this->getmyKeyColumn(), $identifer);
713
714
        return $flexiData;
715
    }
716
717
    /**
718
     * Test if given record exists in FlexiBee.
719
     *
720
     * @param array $data
721
     */
722
    public function recordExists($data = null)
723
    {
724
        if (is_null($data)) {
725
            $data = $this->getData();
726
        }
727
728
        $res = $this->getColumnsFromFlexibee([$this->myKeyColumn],
729
            self::flexiUrl($data));
0 ignored issues
show
Documentation introduced by
self::flexiUrl($data) is of type string, but the function expects a array|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
730
731
        return $res;
732
    }
733
734
    /**
735
     * Vrací z FlexiBee sloupečky podle podmínek.
736
     *
737
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
738
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
739
     *                                     sloupečku
740
     * @return array
741
     */
742 View Code Duplication
    public function getAllFromFlexibee($conditions = null, $indexBy = 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...
743
    {
744
        if (is_int($conditions)) {
745
            $conditions = [$this->getmyKeyColumn() => $conditions];
746
        }
747
748
        $flexiData = $this->getFlexiData('', $conditions);
749
750
        if (!is_null($indexBy)) {
751
            $flexiData = $this->reindexArrayBy($flexiData);
752
        }
753
754
        return $flexiData;
755
    }
756
757
    /**
758
     * Vrací z FlexiBee sloupečky podle podmínek.
759
     *
760
     * @param string[] $columnsList seznam položek
761
     * @param array    $conditions  pole podmínek nebo ID záznamu
762
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
763
     *
764
     * @return array
765
     */
766
    public function getColumnsFromFlexibee($columnsList, $conditions = null,
767
                                           $indexBy = null)
768
    {
769
        if (($columnsList != '*') && !count($columnsList)) {
770
            $this->error('getColumnsFromFlexiBee: Missing ColumnList');
771
772
            return;
773
        }
774
775
        if (is_int($conditions)) {
776
            $conditions = [$this->getmyKeyColumn() => $conditions];
777
        }
778
779
        if (is_array($columnsList)) {
780
            $columns = implode(',', array_unique($columnsList));
781
        } else {
782
            $columns = $columnsList;
783
        }
784
785
        $flexiData = $this->getFlexiData('detail=custom:'.$columns, $conditions);
786
787
        if (!is_null($indexBy)) {
788
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
789
        }
790
791
        return $flexiData;
792
    }
793
794
    /**
795
     * Vrací kód záznamu.
796
     *
797
     * @param mixed $data
798
     *
799
     * @todo papat i string
800
     *
801
     * @return string
802
     */
803
    public function getKod($data = null, $unique = true)
804
    {
805
        $kod = null;
806
807
        if (is_null($data)) {
808
            $data = $this->getData();
809
        }
810
811
        if (is_string($data)) {
812
            $data = [$this->nameColumn => $data];
813
        }
814
815
        if (isset($data['kod'])) {
816
            $kod = $data['kod'];
817
        } else {
818
            if (isset($data[$this->nameColumn])) {
819
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
820
                    \Ease\Sand::rip($data[$this->nameColumn]));
821
            } else {
822
                if (isset($data[$this->myKeyColumn])) {
823
                    $kod = \Ease\Sand::rip($data[$this->myKeyColumn]);
824
                }
825
            }
826
        }
827
828
        if (!strlen($kod)) {
829
            $kod = 'NOTSET';
830
        }
831
832
        if (strlen($kod) > 18) {
833
            $kodfinal = strtoupper(substr($kod, 0, 18));
834
        } else {
835
            $kodfinal = strtoupper($kod);
836
        }
837
838
        if ($unique) {
839
            $counter = 0;
840
            if (count($this->codes)) {
841
                foreach ($this->codes as $codesearch => $keystring) {
842
                    if (strstr($codesearch, $kodfinal)) {
843
                        ++$counter;
844
                    }
845
                }
846
            }
847
            if ($counter) {
848
                $kodfinal = $kodfinal.$counter;
849
            }
850
851
            $this->codes[$kodfinal] = $kod;
852
        }
853
854
        return $kodfinal;
855
    }
856
857
    /**
858
     * Write Operation Result.
859
     *
860
     * @param array  $resultData
861
     * @param string $url        URL
862
     */
863
    public function logResult($resultData = null, $url = null)
864
    {
865
        if (is_null($resultData)) {
866
            $resultData = $this->lastResult;
867
        }
868
        if ($url) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $url of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
869
            $this->logger->addStatusMessage($url);
870
        }
871
872
        if (isset($resultData['results'])) {
873
            $status = null;
0 ignored issues
show
Unused Code introduced by
$status is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
874
            if ($resultData['success'] == 'false') {
875
                $status = 'error';
876
            } else {
877
                $status = 'success';
878
            }
879
            foreach ($resultData['results'] as $result) {
880
                if (isset($result['request-id'])) {
881
                    $rid = $result['request-id'];
882
                } else {
883
                    $rid = '';
884
                }
885
                if (isset($result['errors'])) {
886
                    foreach ($result['errors'] as $error) {
887
                        $message = $error['message'];
888
                        if (isset($error['for'])) {
889
                            $message .= ' for: '.$error['for'];
890
                        }
891
                        if (isset($error['value'])) {
892
                            $message .= ' value:'.$error['value'];
893
                        }
894
                        if (isset($error['code'])) {
895
                            $message .= ' code:'.$error['code'];
896
                        }
897
                        $this->logger->addStatusMessage($rid.': '.$message,
898
                            $status);
899
                    }
900
                }
901
            }
902
        }
903
        if (is_object($this->logger)) {
904
            $this->logger->flush(get_class($this));
905
        }
906
    }
907
908
    /**
909
     * Save RAW Curl Request & Response to files in Temp directory
910
     */
911
    public function saveDebugFiles()
912
    {
913
        $tmpdir = sys_get_temp_dir();
914
        file_put_contents($tmpdir.'/request-'.$this->evidence.'-'.microtime().'.'.$this->format,
915
            $this->postFields);
916
        file_put_contents($tmpdir.'/response-'.$this->evidence.'-'.microtime().'.'.$this->format,
917
            $this->lastCurlResponse);
918
    }
919
920
    /**
921
     * Připraví data pro odeslání do FlexiBee
922
     * 
923
     * @param string $data
924
     */
925
    public function setPostFields($data)
926
    {
927
        $this->postFields = $data;
0 ignored issues
show
Documentation Bug introduced by
It seems like $data of type string is incompatible with the declared type array of property $postFields.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
928
    }
929
930
    /**
931
     * Generuje fragment url pro filtrování.
932
     *
933
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
934
     *
935
     * @param array  $data
936
     * @param string $operator default and/or
937
     *
938
     * @return string
939
     */
940
    public static function flexiUrl(array $data, $operator = 'and')
941
    {
942
        $flexiUrl = '';
0 ignored issues
show
Unused Code introduced by
$flexiUrl is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
943
        $parts    = [];
944
945
        foreach ($data as $column => $value) {
946
            if (is_integer($data[$column]) || is_float($data[$column])) {
947
                $parts[$column] = $column.' eq '.$data[$column];
948
            } elseif (is_bool($data[$column])) {
949
                $parts[$column] = $data[$column] ? $column.' eq true' : $column.' eq false';
950
            } elseif (is_null($data[$column])) {
951
                $parts[$column] = $column." is null";
952
            } elseif ($value == '!null') {
953
                $parts[$column] = $column." is not null";
954
            } else {
955
                $parts[$column] = $column." eq '".$data[$column]."'";
956
            }
957
        }
958
959
        $flexiUrl = implode(' '.$operator.' ', $parts);
960
961
        return $flexiUrl;
962
    }
963
964
    /**
965
     * Vrací identifikátor objektu code: nebo id:
966
     *
967
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
968
     * @return string indentifikátor záznamu reprezentovaného objektem
969
     * @throws Exception data objektu neobsahují kód nebo id
970
     */
971
    public function __toString()
972
    {
973
        $myCode = $this->getDataValue('kod');
974
        if ($myCode) {
975
            $id = 'code:'.$myCode;
976
        } else {
977
            $id = $this->getDataValue('id');
978
            if (!$id) {
979
                throw new \Exception(_('invoice without loaded code: or id: cannot match with statement!'));
980
            }
981
        }
982
        return $id;
983
    }
984
}