Completed
Push — master ( ca076d...5a8969 )
by Vítězslav
07:16
created

FlexiBeeRO::processRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 0
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
     * Parmetry pro URL
209
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Všechny podporované parametry
210
     * @var array
211
     */
212
    public $urlParams = [
213
        'dry-run',
214
        'fail-on-warning',
215
        'report-name',
216
        'report-lang',
217
        'report-sign',
218
        'detail',
219
        'mode',
220
        'limit',
221
        'start',
222
        'order',
223
        'sort',
224
        'add-row-count',
225
        'relations',
226
        'includes',
227
        'use-ext-id',
228
        'use-internal-id',
229
        'stitky-as-ids',
230
        'only-ext-ids',
231
        'no-ext-ids',
232
        'no-ids',
233
        'code-as-id',
234
        'no-http-errors',
235
        'export-settings',
236
        'as-gui',
237
        'code-in-response',
238
        'add-global-version',
239
        'encoding',
240
        'delimeter',
241
        'format',
242
        'auth',
243
        'skupina-stitku',
244
    ];
245
246
    /**
247
     * Třída pro práci s FlexiBee.
248
     *
249
     * @param mixed $init výchozí selektor dat
250
     */
251
    public function __construct($init = null)
252
    {
253
        $this->init = $init;
254
255
        parent::__construct();
256
        $this->setUp();
257
        $this->curlInit();
258
        if ($init) {
259
            $this->processInit($init);
260
        }
261
    }
262
263
    /**
264
     * SetUp Object to be ready for connect
265
     */
266
    public function setUp()
267
    {
268
        if (is_null($this->company) && defined('FLEXIBEE_COMPANY')) {
269
            $this->company = constant('FLEXIBEE_COMPANY');
270
        }
271
        if (is_null($this->url) && defined('FLEXIBEE_URL')) {
272
            $this->url = constant('FLEXIBEE_URL');
273
        }
274
275
        if (is_null($this->user) && defined('FLEXIBEE_LOGIN')) {
276
            $this->user = constant('FLEXIBEE_LOGIN');
277
        }
278
279
        if (is_null($this->password) && defined('FLEXIBEE_PASSWORD')) {
280
            $this->password = constant('FLEXIBEE_PASSWORD');
281
        }
282
    }
283
284
    /**
285
     * Inicializace CURL
286
     */
287
    public function curlInit()
288
    {
289
        $this->curl = \curl_init(); // create curl resource
290
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); // return content as a string from curl_exec
291
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true); // follow redirects (compatibility for future changes in FlexiBee)
292
        curl_setopt($this->curl, CURLOPT_HTTPAUTH, true);       // HTTP authentication
293
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); // FlexiBee by default uses Self-Signed certificates
294
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
295
        curl_setopt($this->curl, CURLOPT_VERBOSE, true); // For debugging
296
        curl_setopt($this->curl, CURLOPT_USERPWD,
297
            $this->user.':'.$this->password); // set username and password
298
    }
299
300
    /**
301
     * Zinicializuje objekt dle daných dat
302
     * 
303
     * @param mixed $init
304
     */
305
    public function processInit($init)
306
    {
307
        if (is_integer($init)) {
308
            $this->loadFromFlexiBee($init);
309
        } elseif (is_array($init)) {
310
            $this->takeData($init);
311
        }
312
    }
313
314
    /**
315
     * Nastaví Evidenci pro Komunikaci.
316
     *
317
     * @param string $evidence
318
     */
319
    public function setEvidence($evidence)
320
    {
321
        $this->evidence = $evidence;
322
    }
323
324
    /**
325
     * Vrací právě používanou evidenci pro komunikaci
326
     * 
327
     * @return string
328
     */
329
    public function getEvidence()
330
    {
331
        return $this->evidence;
332
    }
333
334
    /**
335
     * Převede rekurzivně Objekt na pole.
336
     *
337
     * @param object|array $object
338
     *
339
     * @return array
340
     */
341
    public static function object2array($object)
342
    {
343
        $result = null;
344
        if (is_object($object)) {
345
            $objectData = get_object_vars($object);
346
            if (is_array($objectData) && count($objectData)) {
347
                $result = array_map('self::object2array', $objectData);
348
            }
349 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...
350
            if (is_array($object)) {
351
                foreach ($object as $item => $value) {
352
                    $result[$item] = self::object2array($value);
353
                }
354
            } else {
355
                $result = $object;
356
            }
357
        }
358
359
        return $result;
360
    }
361
362
    /**
363
     * Převede rekurzivně v poli všechny objekty na jejich identifikátory.
364
     *
365
     * @param object|array $object
366
     *
367
     * @return array
368
     */
369
    public static function objectToID($object)
370
    {
371
        $result = null;
372
        if (is_object($object)) {
373
            $result = $object->__toString();
374 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...
375
            if (is_array($object)) {
376
                foreach ($object as $item => $value) {
377
                    $result[$item] = self::objectToID($value);
378
                }
379
            } else { //String
380
                $result = $object;
381
            }
382
        }
383
384
        return $result;
385
    }
386
387
    /**
388
     * Vrací základní URL pro užitou evidenci
389
     *
390
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
391
     * @param string $urlSuffix
392
     */
393
    public function getEvidenceURL($urlSuffix = null)
394
    {
395
        if (is_null($urlSuffix)) {
396
            $urlSuffix = $this->evidence;
397
        }
398
        return $this->url.$this->prefix.$this->company.'/'.$urlSuffix;
399
    }
400
401
    /**
402
     * Funkce, která provede I/O operaci a vyhodnotí výsledek.
403
     *
404
     * @param string $urlSuffix část URL za identifikátorem firmy.
405
     * @param string $method    HTTP/REST metoda
406
     * @param string $format    Requested format
407
     * @return array|boolean Výsledek operace
408
     */
409
    public function performRequest($urlSuffix = null, $method = 'GET',
410
                                   $format = null)
411
    {
412
413
        $url = $this->getEvidenceURL($urlSuffix);
414
415
        $responseCode = $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...
416
417
        if (is_null($format)) {
418
            $format = $this->format;
419
        }
420
421
        switch ($responseCode) {
422
            case 200:
423
            case 201:
424
                // Parse response
425
                $responseDecoded = [];
426
427
                switch ($format) {
428
                    case 'json':
429
                        $responseDecoded = json_decode($this->lastCurlResponse,
430
                            true, 10);
431
                        if (($method == 'PUT') && isset($responseDecoded[$this->nameSpace][$this->resultField][0]['id'])) {
432
                            $this->lastInsertedID = $responseDecoded[$this->nameSpace][$this->resultField][0]['id'];
433
                        } else {
434
                            $this->lastInsertedID = null;
435
                        }
436
                        $decodeError = json_last_error_msg();
437
                        if ($decodeError != 'No error') {
438
                            $this->addStatusMessage($decodeError, 'error');
439
                        }
440
                        break;
441
                    case 'xml':
442
                        if (strlen($this->lastCurlResponse)) {
443
                            $responseDecoded = self::xml2array($this->lastCurlResponse);
444
                        } else {
445
                            $responseDecoded = null;
446
                        }
447
                        break;
448
                }
449
450
                // Get response body root automatically
451
                if (isset($responseDecoded[$this->nameSpace])) {
452
                    $responseDecoded = $responseDecoded[$this->nameSpace];
453
                }
454
455
                $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...
456
                $response         = $responseDecoded;
457
458
                break;
459
460
            default: //Some goes wrong
461
                $this->lastCurlError = curl_error($this->curl);
462
                switch ($format) {
463
                    case 'json':
464
                        $response = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/',
465
                            function ($match) {
466
                            return mb_convert_encoding(pack('H*', $match[1]),
467
                                'UTF-8', 'UCS-2BE');
468
                        }, $this->lastCurlResponse);
469
                        $response = (json_encode(json_decode($response, true, 10),
470
                                JSON_PRETTY_PRINT));
471
                        break;
472
                    case 'xml':
473
                        if (strlen($this->lastCurlResponse)) {
474
                            $response = self::xml2array($this->lastCurlResponse);
475
                        }
476
                        break;
477
                }
478
479
                if (is_array($response)) {
480
                    $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...
481
                } elseif (strlen($response) && ($response != 'null')) {
482
                    $result = urldecode(http_build_query(self::object2array(current(json_decode($response)))));
483
                } else {
484
                    $result = null;
485
                }
486
487
                if ($response == 'null') {
488
                    if ($this->lastResponseCode == 200) {
489
                        $response = true;
490
                    } else {
491
                        $response = null;
492
                    }
493
                } else {
494
                    if (is_string($response)) {
495
                        $response = self::object2array(current(json_decode($response)));
496
                    }
497
                }
498
499
                if (is_array($response) && ($this->lastResponseCode == 400)) {
500
                    $this->logResult($response);
501
                } else {
502
                    $this->addStatusMessage(sprintf('Error (HTTP %d): <pre>%s</pre> %s',
503
                            curl_getinfo($this->curl, CURLINFO_HTTP_CODE),
504
                            $result, $this->lastCurlError), 'error');
505
                    $this->addStatusMessage($url, 'info');
506
                    if (count($this->postFields)) {
507
                        $this->addStatusMessage(urldecode(http_build_query($this->postFields)),
508
                            'debug');
509
                    }
510
                }
511
512
513
                break;
514
        }
515
        return $response;
516
    }
517
518
    /**
519
     * Vykonej HTTP požadavek
520
     *
521
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
522
     * @param string $url    URL požadavku
523
     * @param strinf $method HTTP Method GET|POST|PUT|OPTIONS|DELETE
524
     * @param string $format požadovaný formát komunikace
525
     * @return int HTTP Response CODE
526
     */
527
    public function doCurlRequest($url, $method, $format = null)
528
    {
529
        if (is_null($format)) {
530
            $format = $this->format;
531
        }
532
        curl_setopt($this->curl, CURLOPT_URL, $url);
533
// Nastavení samotné operace
534
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
535
//Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411
536
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
537
538
        $httpHeaders = $this->defaultHttpHeaders;
539
        switch ($format) {
540
            case 'json':
541
                $httpHeaders['Accept']       = 'application/json';
542
                $httpHeaders['Content-Type'] = 'application/json';
543
544
                break;
545
            case 'xml':
546
                $httpHeaders['Accept']       = 'application/xml';
547
                $httpHeaders['Content-Type'] = 'application/xml';
548
                break;
549
        }
550
551
        $httpHeadersFinal = [];
552
        foreach ($httpHeaders as $key => $value) {
553
            $httpHeadersFinal[] = $key.': '.$value;
554
        }
555
556
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
557
558
// Proveď samotnou operaci
559
        $this->lastCurlResponse = curl_exec($this->curl);
560
561
        $this->info = curl_getinfo($this->curl);
562
563
        $this->lastResponseCode = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
564
        return $this->lastResponseCode;
565
    }
566
567
    /**
568
     * Nastaví druh prováděné akce.
569
     *
570
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
571
     * @param string $action
572
     * @return boolean
573
     */
574
    public function setAction($action)
575
    {
576
        $result = false;
577
        if (is_null($this->actionsAvailable)) {
578
            $this->action = $action;
579
            $result       = true;
580
        } else {
581
            if (array_search($action, $this->actionsAvailable)) {
582
                $this->action = $action;
583
                $result       = true;
584
            }
585
        }
586
        return $result;
587
    }
588
589
    /**
590
     * Convert XML to array.
591
     *
592
     * @param string $xml
593
     *
594
     * @return array
595
     */
596
    public static function xml2array($xml)
597
    {
598
        $arr = [];
599
600
        if (is_string($xml)) {
601
            $xml = simplexml_load_string($xml);
602
        }
603
604
        foreach ($xml->children() as $r) {
605
            if (count($r->children()) == 0) {
606
                $arr[$r->getName()] = strval($r);
607
            } else {
608
                $arr[$r->getName()][] = self::xml2array($r);
609
            }
610
        }
611
612
        return $arr;
613
    }
614
615
    /**
616
     * Odpojení od FlexiBee.
617
     */
618
    public function disconnect()
619
    {
620
        if (is_resource($this->curl)) {
621
            curl_close($this->curl);
622
        }
623
        $this->curl = null;
624
    }
625
626
    public function __destruct()
627
    {
628
        $this->disconnect();
629
    }
630
631
    /**
632
     * Načte data z FlexiBee.
633
     *
634
     * @param string $suffix dotaz
635
     */
636
    public function loadFlexiData($suffix = null)
637
    {
638
        return $this->takeData($this->getFlexiData($suffix));
639
    }
640
641
    /**
642
     * Načte řádek dat z FlexiBee.
643
     *
644
     * @param int $recordID id požadovaného záznamu
645
     *
646
     * @return array
647
     */
648
    public function getFlexiRow($recordID)
649
    {
650
        $record   = null;
651
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
652
        if (isset($response[$this->evidence])) {
653
            $record = $response[$this->evidence][0];
654
        }
655
656
        return $record;
657
    }
658
659
    /**
660
     * Oddělí z pole podmínek ty jenž patří za ? v URL požadavku
661
     *
662
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
663
     * @param array $conditions pole podmínek   - rendrují se do ()
664
     * @param array $urlParams  pole parametrů  - rendrují za ?
665
     */
666
    public function extractUrlParams(&$conditions, &$urlParams)
667
    {
668
        foreach ($this->urlParams as $urlParam) {
669
            if (isset($conditions[$urlParam])) {
670
                \Ease\Sand::divDataArray($conditions, $urlParams, $urlParam);
671
            }
672
        }
673
    }
674
675
    /**
676
     * Načte data z FlexiBee.
677
     *
678
     * @param string $suffix     dotaz
679
     * @param string|array $conditions Volitelný filtrovací výraz
680
     */
681
    public function getFlexiData($suffix = null, $conditions = null)
682
    {
683
        $urlParams = $this->defaultUrlParams;
684
        if (!is_null($conditions)) {
685
            if (is_array($conditions)) {
686
                $this->extractUrlParams($conditions, $urlParams);
687
                $conditions = $this->flexiUrl($conditions);
688
            }
689
690
            if (strlen($conditions) && ($conditions[0] != '/')) {
691
                $conditions = '/'.rawurlencode('('.($conditions).')');
692
            }
693
        } else {
694
            $conditions = '';
695
        }
696
        if (strlen($suffix)) {
697
            $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.$suffix.'&'.http_build_query($urlParams),
698
                'GET');
699
        } else {
700
            $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.http_build_query($urlParams),
701
                'GET');
702
        }
703
        if (isset($transactions[$this->evidence])) {
704
            $result = $transactions[$this->evidence];
705
        } else {
706
            $result = $transactions;
707
        }
708
709
        return $result;
710
    }
711
712
    /**
713
     * Načte záznam z FlexiBee.
714
     *
715
     * @param int $id ID záznamu
716
     *
717
     * @return int počet načtených položek
718
     */
719 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...
720
    {
721
        $data = [];
722
        if (is_null($id)) {
723
            $id = $this->getMyKey();
724
        }
725
726
        $flexidata = $this->getFlexiData(null, '/'.$id);
727
        if (count($flexidata) == 1) {
728
            $data = current($flexidata);
729
        }
730
        return $this->takeData($data);
731
    }
732
733
    /**
734
     * Převede data do Json formátu pro FlexiBee.
735
     *
736
     * @param array $data
737
     *
738
     * @return string
739
     */
740
    public function jsonizeData($data)
741
    {
742
        $jsonize = [
743
            $this->nameSpace => [
744
                '@version' => $this->protoVersion,
745
                $this->evidence => $this->objectToID($data),
746
            ],
747
        ];
748
749
        if (!is_null($this->action)) {
750
            $jsonize[$this->nameSpace][$this->evidence.'@action'] = $this->action;
751
            $this->action                                         = null;
752
        }
753
754
        return json_encode($jsonize);
755
    }
756
757
    /**
758
     * Test if given record ID exists in FlexiBee.
759
     *
760
     * @param string|int $identifer
761
     */
762
    public function idExists($identifer = null)
763
    {
764
        if (is_null($identifer)) {
765
            $identifer = $this->getMyKey();
766
        }
767
        $flexiData = $this->getFlexiData(
768
            'detail=custom:'.$this->getmyKeyColumn(), $identifer);
769
770
        return $flexiData;
771
    }
772
773
    /**
774
     * Test if given record exists in FlexiBee.
775
     *
776
     * @param array $data
777
     */
778
    public function recordExists($data = null)
779
    {
780
        if (is_null($data)) {
781
            $data = $this->getData();
782
        }
783
784
        $res = $this->getColumnsFromFlexibee([$this->myKeyColumn],
785
            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...
786
787
        return $res;
788
    }
789
790
    /**
791
     * Vrací z FlexiBee sloupečky podle podmínek.
792
     *
793
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
794
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
795
     *                                     sloupečku
796
     * @return array
797
     */
798 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...
799
    {
800
        if (is_int($conditions)) {
801
            $conditions = [$this->getmyKeyColumn() => $conditions];
802
        }
803
804
        $flexiData = $this->getFlexiData('', $conditions);
805
806
        if (!is_null($indexBy)) {
807
            $flexiData = $this->reindexArrayBy($flexiData);
808
        }
809
810
        return $flexiData;
811
    }
812
813
    /**
814
     * Vrací z FlexiBee sloupečky podle podmínek.
815
     *
816
     * @param string[] $columnsList seznam položek
817
     * @param array    $conditions  pole podmínek nebo ID záznamu
818
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
819
     *
820
     * @return array
821
     */
822
    public function getColumnsFromFlexibee($columnsList, $conditions = null,
823
                                           $indexBy = null)
824
    {
825
        if (($columnsList != '*') && !count($columnsList)) {
826
            $this->error('getColumnsFromFlexiBee: Missing ColumnList');
827
828
            return;
829
        }
830
831
        if (is_int($conditions)) {
832
            $conditions = [$this->getmyKeyColumn() => $conditions];
833
        }
834
835
        if (is_array($columnsList)) {
836
            $columns = implode(',', array_unique($columnsList));
837
        } else {
838
            $columns = $columnsList;
839
        }
840
841
        $flexiData = $this->getFlexiData('detail=custom:'.$columns, $conditions);
842
843
        if (!is_null($indexBy)) {
844
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
845
        }
846
847
        return $flexiData;
848
    }
849
850
    /**
851
     * Vrací kód záznamu.
852
     *
853
     * @param mixed $data
854
     *
855
     * @todo papat i string
856
     *
857
     * @return string
858
     */
859
    public function getKod($data = null, $unique = true)
860
    {
861
        $kod = null;
862
863
        if (is_null($data)) {
864
            $data = $this->getData();
865
        }
866
867
        if (is_string($data)) {
868
            $data = [$this->nameColumn => $data];
869
        }
870
871
        if (isset($data['kod'])) {
872
            $kod = $data['kod'];
873
        } else {
874
            if (isset($data[$this->nameColumn])) {
875
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
876
                    \Ease\Sand::rip($data[$this->nameColumn]));
877
            } else {
878
                if (isset($data[$this->myKeyColumn])) {
879
                    $kod = \Ease\Sand::rip($data[$this->myKeyColumn]);
880
                }
881
            }
882
        }
883
884
        if (!strlen($kod)) {
885
            $kod = 'NOTSET';
886
        }
887
888
        if (strlen($kod) > 18) {
889
            $kodfinal = strtoupper(substr($kod, 0, 18));
890
        } else {
891
            $kodfinal = strtoupper($kod);
892
        }
893
894
        if ($unique) {
895
            $counter = 0;
896
            if (count($this->codes)) {
897
                foreach ($this->codes as $codesearch => $keystring) {
898
                    if (strstr($codesearch, $kodfinal)) {
899
                        ++$counter;
900
                    }
901
                }
902
            }
903
            if ($counter) {
904
                $kodfinal = $kodfinal.$counter;
905
            }
906
907
            $this->codes[$kodfinal] = $kod;
908
        }
909
910
        return $kodfinal;
911
    }
912
913
    /**
914
     * Write Operation Result.
915
     *
916
     * @param array  $resultData
917
     * @param string $url        URL
918
     */
919
    public function logResult($resultData = null, $url = null)
920
    {
921
        if (is_null($resultData)) {
922
            $resultData = $this->lastResult;
923
        }
924
        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...
925
            $this->logger->addStatusMessage($url);
926
        }
927
928
        if (isset($resultData['results'])) {
929
            $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...
930
            if ($resultData['success'] == 'false') {
931
                $status = 'error';
932
            } else {
933
                $status = 'success';
934
            }
935
            foreach ($resultData['results'] as $result) {
936
                if (isset($result['request-id'])) {
937
                    $rid = $result['request-id'];
938
                } else {
939
                    $rid = '';
940
                }
941
                if (isset($result['errors'])) {
942
                    foreach ($result['errors'] as $error) {
943
                        $message = $error['message'];
944
                        if (isset($error['for'])) {
945
                            $message .= ' for: '.$error['for'];
946
                        }
947
                        if (isset($error['value'])) {
948
                            $message .= ' value:'.$error['value'];
949
                        }
950
                        if (isset($error['code'])) {
951
                            $message .= ' code:'.$error['code'];
952
                        }
953
                        $this->logger->addStatusMessage($rid.': '.$message,
954
                            $status);
955
                    }
956
                }
957
            }
958
        }
959
        if (is_object($this->logger)) {
960
            $this->logger->flush(get_class($this));
961
        }
962
    }
963
964
    /**
965
     * Save RAW Curl Request & Response to files in Temp directory
966
     */
967
    public function saveDebugFiles()
968
    {
969
        $tmpdir = sys_get_temp_dir();
970
        file_put_contents($tmpdir.'/request-'.$this->evidence.'-'.microtime().'.'.$this->format,
971
            $this->postFields);
972
        file_put_contents($tmpdir.'/response-'.$this->evidence.'-'.microtime().'.'.$this->format,
973
            $this->lastCurlResponse);
974
    }
975
976
    /**
977
     * Připraví data pro odeslání do FlexiBee
978
     * 
979
     * @param string $data
980
     */
981
    public function setPostFields($data)
982
    {
983
        $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...
984
    }
985
986
    /**
987
     * Generuje fragment url pro filtrování.
988
     *
989
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
990
     *
991
     * @param array  $data
992
     * @param string $operator default and/or
993
     *
994
     * @return string
995
     */
996
    public static function flexiUrl(array $data, $operator = 'and')
997
    {
998
        $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...
999
        $parts    = [];
1000
1001
        foreach ($data as $column => $value) {
1002
            if (is_integer($data[$column]) || is_float($data[$column])) {
1003
                $parts[$column] = $column.' eq '.$data[$column];
1004
            } elseif (is_bool($data[$column])) {
1005
                $parts[$column] = $data[$column] ? $column.' eq true' : $column.' eq false';
1006
            } elseif (is_null($data[$column])) {
1007
                $parts[$column] = $column." is null";
1008
            } elseif ($value == '!null') {
1009
                $parts[$column] = $column." is not null";
1010
            } else {
1011
                $parts[$column] = $column." eq '".$data[$column]."'";
1012
            }
1013
        }
1014
1015
        $flexiUrl = implode(' '.$operator.' ', $parts);
1016
1017
        return $flexiUrl;
1018
    }
1019
1020
    /**
1021
     * Vrací identifikátor objektu code: nebo id:
1022
     *
1023
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1024
     * @return string indentifikátor záznamu reprezentovaného objektem
1025
     * @throws Exception data objektu neobsahují kód nebo id
1026
     */
1027
    public function __toString()
1028
    {
1029
        $myCode = $this->getDataValue('kod');
1030
        if ($myCode) {
1031
            $id = 'code:'.$myCode;
1032
        } else {
1033
            $id = $this->getDataValue('id');
1034
            if (!$id) {
1035
                throw new \Exception(_('invoice without loaded code: or id: cannot match with statement!'));
1036
            }
1037
        }
1038
        return $id;
1039
    }
1040
}