Completed
Push — master ( 9f37b9...417a27 )
by Vítězslav
08:08
created

FlexiBeeRO::getRelationsInfo()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 4
nop 1
dl 0
loc 12
rs 9.4285
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,2016 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
     * Version of FlexiPeeHP library
20
     *
21
     * @var string
22
     */
23
    static public $libVersion = '1.6.3.8';
24
25
    /**
26
     * Základní namespace pro komunikaci s FlexiBee.
27
     * Basic namespace for communication with FlexiBee
28
     *
29
     * @var string Jmený prostor datového bloku odpovědi
30
     */
31
    public $nameSpace = 'winstrom';
32
33
    /**
34
     * Datový blok v poli odpovědi.
35
     * Data block in response field.
36
     *
37
     * @var string
38
     */
39
    public $resultField = 'results';
40
41
    /**
42
     * Verze protokolu použitého pro komunikaci.
43
     * Communication protocol version used.
44
     *
45
     * @var string Verze použitého API
46
     */
47
    public $protoVersion = '1.0';
48
49
    /**
50
     * Evidence užitá objektem.
51
     * Evidence used by object
52
     *
53
     * @link https://demo.flexibee.eu/c/demo/evidence-list Přehled evidencí
54
     * @var string
55
     */
56
    public $evidence = null;
57
58
    /**
59
     * Výchozí formát pro komunikaci.
60
     * Default communication format.
61
     *
62
     * @link https://www.flexibee.eu/api/dokumentace/ref/format-types Přehled možných formátů
63
     *
64
     * @var string json|xml|...
65
     */
66
    public $format = 'json';
67
68
    /**
69
     * Curl Handle.
70
     *
71
     * @var resource
72
     */
73
    public $curl = null;
74
75
    /**
76
     * @link https://demo.flexibee.eu/devdoc/company-identifier Identifikátor firmy
77
     * @var string
78
     */
79
    public $company = null;
80
81
    /**
82
     * Server[:port]
83
     * @var string
84
     */
85
    public $url = null;
86
87
    /**
88
     * REST API Username
89
     * @var string
90
     */
91
    public $user = null;
92
93
    /**
94
     * REST API Password
95
     * @var string
96
     */
97
    public $password = null;
98
99
    /**
100
     * @var array Pole HTTP hlaviček odesílaných s každým požadavkem
101
     */
102
    public $defaultHttpHeaders = ['User-Agent' => 'FlexiPeeHP'];
103
104
    /**
105
     * Default additional request url parameters after question mark
106
     * 
107
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls   Common params
108
     * @link https://www.flexibee.eu/api/dokumentace/ref/paging Paging params
109
     * @var array
110
     */
111
    public $defaultUrlParams = ['limit' => 0];
112
113
    /**
114
     * Identifikační řetězec.
115
     *
116
     * @var string
117
     */
118
    public $init = null;
119
120
    /**
121
     * Sloupeček s názvem.
122
     *
123
     * @var string
124
     */
125
    public $nameColumn = 'nazev';
126
127
    /**
128
     * Sloupeček obsahující datum vložení záznamu do shopu.
129
     *
130
     * @var string
131
     */
132
    public $myCreateColumn = 'false';
133
134
    /**
135
     * Slopecek obsahujici datum poslení modifikace záznamu do shopu.
136
     *
137
     * @var string
138
     */
139
    public $myLastModifiedColumn = 'lastUpdate';
140
141
    /**
142
     * Klíčový idendifikátor záznamu.
143
     *
144
     * @var string
145
     */
146
    public $fbKeyColumn = 'id';
147
148
    /**
149
     * Informace o posledním HTTP requestu.
150
     *
151
     * @var *
152
     */
153
    public $info;
154
155
    /**
156
     * Informace o poslední HTTP chybě.
157
     *
158
     * @var string
159
     */
160
    public $lastCurlError = null;
161
162
    /**
163
     * Used codes storage.
164
     *
165
     * @var array
166
     */
167
    public $codes = null;
168
169
    /**
170
     * Last Inserted ID.
171
     *
172
     * @var int
173
     */
174
    public $lastInsertedID = null;
175
176
    /**
177
     * Default Line Prefix.
178
     *
179
     * @var string
180
     */
181
    public $prefix = '/c/';
182
183
    /**
184
     * Raw Content of last curl response
185
     * 
186
     * @var string
187
     */
188
    public $lastCurlResponse;
189
190
    /**
191
     * HTTP Response code of last request
192
     *
193
     * @var int
194
     */
195
    public $lastResponseCode = null;
196
197
    /**
198
     * Array of fields for next curl POST operation
199
     *
200
     * @var array
201
     */
202
    protected $postFields = [];
203
204
    /**
205
     * Last operation result data or message(s)
206
     *
207
     * @var array
208
     */
209
    public $lastResult = null;
210
211
    /**
212
     * Nuber from  @rowCount
213
     * @var int
214
     */
215
    public $rowCount = null;
216
217
    /**
218
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
219
     * @var string
220
     */
221
    protected $action;
222
223
    /**
224
     * Pole akcí které podporuje ta která evidence
225
     * @link https://demo.flexibee.eu/c/demo/faktura-vydana/actions.json Např. Akce faktury
226
     * @var array
227
     */
228
    public $actionsAvailable = null;
229
230
    /**
231
     * Parmetry pro URL
232
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Všechny podporované parametry
233
     * @var array
234
     */
235
    public $urlParams = [
236
        'dry-run',
237
        'fail-on-warning',
238
        'report-name',
239
        'report-lang',
240
        'report-sign',
241
        'detail',
242
        'mode',
243
        'limit',
244
        'start',
245
        'order',
246
        'sort',
247
        'add-row-count',
248
        'relations',
249
        'includes',
250
        'use-ext-id',
251
        'use-internal-id',
252
        'stitky-as-ids',
253
        'only-ext-ids',
254
        'no-ext-ids',
255
        'no-ids',
256
        'code-as-id',
257
        'no-http-errors',
258
        'export-settings',
259
        'as-gui',
260
        'code-in-response',
261
        'add-global-version',
262
        'encoding',
263
        'delimeter',
264
        'format',
265
        'auth',
266
        'skupina-stitku',
267
        'dir',
268
        'xpath', // See: https://www.flexibee.eu/api/dokumentace/ref/xpath/
269
        'dry-run', // See: https://www.flexibee.eu/api/dokumentace/ref/dry-run/
270
        'inDesktopApp' // Note: Undocumented function (html only)
271
    ];
272
273
    /**
274
     * Class for read only interaction with FlexiBee.
275
     *
276
     * @param mixed $init default record id or initial data
277
     * @param array $options Connection settings override
278
     */
279
    public function __construct($init = null, $options = [])
280
    {
281
        $this->init = $init;
282
283
        parent::__construct();
284
        $this->setUp($options);
285
        $this->curlInit();
286
        if (!is_null($init)) {
287
            $this->processInit($init);
288
        }
289
    }
290
291
    /**
292
     * SetUp Object to be ready for connect
293
     *
294
     * @param array $options Object Options
295
     */
296
    public function setUp($options = [])
297
    {
298 View Code Duplication
        if (isset($options['company'])) {
1 ignored issue
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...
299
            $this->company = $options['company'];
300
        } else {
301
            if (is_null($this->company) && defined('FLEXIBEE_COMPANY')) {
302
                $this->company = constant('FLEXIBEE_COMPANY');
303
            }
304
        }
305 View Code Duplication
        if (isset($options['url'])) {
1 ignored issue
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...
306
            $this->url = $options['url'];
307
        } else {
308
            if (is_null($this->url) && defined('FLEXIBEE_URL')) {
309
                $this->url = constant('FLEXIBEE_URL');
310
            }
311
        }
312 View Code Duplication
        if (isset($options['user'])) {
1 ignored issue
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...
313
            $this->user = $options['user'];
314
        } else {
315
            if (is_null($this->user) && defined('FLEXIBEE_LOGIN')) {
316
                $this->user = constant('FLEXIBEE_LOGIN');
317
            }
318
        }
319 View Code Duplication
        if (isset($options['password'])) {
1 ignored issue
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...
320
            $this->password = $options['password'];
321
        } else {
322
            if (is_null($this->password) && defined('FLEXIBEE_PASSWORD')) {
323
                $this->password = constant('FLEXIBEE_PASSWORD');
324
            }
325
        }
326
        if (isset($options['evidence'])) {
327
            $this->setEvidence($options['evidence']);
328
        }
329
        if (isset($options['prefix'])) {
330
            $this->setPrefix($options['prefix']);
331
        }
332
    }
333
334
    /**
335
     * Inicializace CURL
336
     */
337
    public function curlInit()
338
    {
339
        $this->curl = \curl_init(); // create curl resource
340
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); // return content as a string from curl_exec
341
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true); // follow redirects (compatibility for future changes in FlexiBee)
342
        curl_setopt($this->curl, CURLOPT_HTTPAUTH, true);       // HTTP authentication
343
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); // FlexiBee by default uses Self-Signed certificates
344
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
345
        curl_setopt($this->curl, CURLOPT_VERBOSE, ($this->debug === true)); // For debugging
346
        curl_setopt($this->curl, CURLOPT_USERPWD,
347
            $this->user.':'.$this->password); // set username and password
348
    }
349
350
    /**
351
     * Zinicializuje objekt dle daných dat
352
     * 
353
     * @param mixed $init
354
     */
355
    public function processInit($init)
356
    {
357
        if (is_integer($init)) {
358
            $this->loadFromFlexiBee($init);
359
        } elseif (is_array($init)) {
360
            $this->takeData($init);
361
        } elseif (strstr($init, 'code:')) {
362
            $this->loadFromFlexiBee($init);
363
        }
364
    }
365
366
    /**
367
     * Set URL prefix
368
     *
369
     * @param string $prefix
370
     */
371
    public function setPrefix($prefix)
372
    {
373
        switch ($prefix) {
374
            case 'a': //Access
375
            case 'c': //Company
376
            case 'u': //User
377
            case 'g': //License Groups
378
            case 'admin':
379
            case 'status':
380
            case 'login-logout':
381
                $this->prefix = '/'.$prefix.'/';
382
                break;
383
            case null:
384
            case '':
385
            case '/':
386
                $this->prefix = '';
387
                break;
388
            default:
389
                throw new \Exception(sprintf('Unknown prefix %s', $prefix));
390
                break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
391
        }
392
    }
393
394
    /**
395
     * Nastaví Evidenci pro Komunikaci.
396
     * Set evidence for communication
397
     *
398
     * @param string $evidence evidence pathName to use
399
     * @return boolean evidence switching status
400
     */
401
    public function setEvidence($evidence)
402
    {
403
        $result = null;
0 ignored issues
show
Unused Code introduced by
$result 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...
404
        switch ($this->prefix) {
405
            case '/c/':
406
                if (array_key_exists($evidence, EvidenceList::$name)) {
407
                    $this->evidence = $evidence;
408
                    $result         = true;
409
                } else {
410
                    throw new \Exception(sprintf('Try to set unsupported evidence %s',
411
                        $evidence));
412
                }
413
                break;
414
            default:
415
                $this->evidence = $evidence;
416
                $result         = true;
417
                break;
418
        }
419
        return $result;
420
    }
421
422
    /**
423
     * Vrací právě používanou evidenci pro komunikaci
424
     * Obtain current used evidence
425
     *
426
     * @return string
427
     */
428
    public function getEvidence()
429
    {
430
        return $this->evidence;
431
    }
432
433
    /**
434
     * Set used company.
435
     * Nastaví Firmu.
436
     *
437
     * @param string $company
438
     */
439
    public function setCompany($company)
440
    {
441
        $this->company = $company;
442
    }
443
444
    /**
445
     * Obtain company now used
446
     * Vrací právě používanou firmu
447
     *
448
     * @return string
449
     */
450
    public function getCompany()
451
    {
452
        return $this->company;
453
    }
454
455
    /**
456
     * Vrací název evidence použité v odpovědích z FlexiBee
457
     *
458
     * @return string
459
     */
460
    public function getResponseEvidence()
461
    {
462
        switch ($this->evidence) {
463
            case 'c':
464
                $evidence = 'companies';
465
                break;
466
            default:
467
                $evidence = $this->getEvidence();
468
                break;
469
        }
470
        return $evidence;
471
    }
472
473
    /**
474
     * Převede rekurzivně Objekt na pole.
475
     *
476
     * @param object|array $object
477
     *
478
     * @return array
479
     */
480
    public static function object2array($object)
481
    {
482
        $result = null;
483
        if (is_object($object)) {
484
            $objectData = get_object_vars($object);
485
            if (is_array($objectData) && count($objectData)) {
486
                $result = array_map('self::object2array', $objectData);
487
            }
488 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...
489
            if (is_array($object)) {
490
                foreach ($object as $item => $value) {
491
                    $result[$item] = self::object2array($value);
492
                }
493
            } else {
494
                $result = $object;
495
            }
496
        }
497
498
        return $result;
499
    }
500
501
    /**
502
     * Převede rekurzivně v poli všechny objekty na jejich identifikátory.
503
     *
504
     * @param object|array $object
505
     *
506
     * @return array
507
     */
508
    public static function objectToID($object)
509
    {
510
        $result = null;
511
        if (is_object($object)) {
512
            $result = $object->__toString();
513 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...
514
            if (is_array($object)) {
515
                foreach ($object as $item => $value) {
516
                    $result[$item] = self::objectToID($value);
517
                }
518
            } else { //String
519
                $result = $object;
520
            }
521
        }
522
523
        return $result;
524
    }
525
526
    /**
527
     * Return basic URL for used Evidence
528
     *
529
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
530
     * @param string $urlSuffix
531
     */
532
    public function getEvidenceURL($urlSuffix = null)
533
    {
534
        if (is_null($urlSuffix)) {
535
            $urlSuffix = $this->getEvidence();
536
        } elseif ($urlSuffix[0] == ';') {
537
            $urlSuffix = $this->getEvidence().$urlSuffix;
538
        }
539
        return $this->url.$this->prefix.$this->company.'/'.$urlSuffix;
540
    }
541
542
    /**
543
     * Funkce, která provede I/O operaci a vyhodnotí výsledek.
544
     *
545
     * @param string $urlSuffix část URL za identifikátorem firmy.
546
     * @param string $method    HTTP/REST metoda
547
     * @param string $format    Requested format
548
     * @return array|boolean Výsledek operace
549
     */
550
    public function performRequest($urlSuffix = null, $method = 'GET',
551
                                   $format = null)
552
    {
553
        $this->rowCount = null;
554
        $url            = $this->getEvidenceURL($urlSuffix);
555
556
        $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...
557
558
        if (is_null($format)) {
559
            $format = $this->format;
560
        }
561
562
        switch ($responseCode) {
563
            case 200:
564
            case 201:
565
                // Parse response
566
                $responseDecoded = [];
567
568
                switch ($format) {
569
                    case 'json':
570
                        $responseDecoded = json_decode($this->lastCurlResponse,
571
                            true, 10);
572
                        if (($method == 'PUT') && isset($responseDecoded[$this->nameSpace][$this->resultField][0]['id'])) {
573
                            $this->lastInsertedID = $responseDecoded[$this->nameSpace][$this->resultField][0]['id'];
574
                            $this->setMyKey($this->lastInsertedID);
575
                        } else {
576
                            $this->lastInsertedID = null;
577
                            if (isset($responseDecoded[$this->nameSpace]['@rowCount'])) {
578
                                $this->rowCount = (int) $responseDecoded[$this->nameSpace]['@rowCount'];
579
                            }
580
                        }
581
                        $decodeError = json_last_error_msg();
582
                        if ($decodeError != 'No error') {
583
                            $this->addStatusMessage($decodeError, 'error');
584
                        }
585
                        break;
586
                    case 'xml':
587
                        if (strlen($this->lastCurlResponse)) {
588
                            $responseDecoded = self::xml2array($this->lastCurlResponse);
589
                        } else {
590
                            $responseDecoded = null;
591
                        }
592
                        break;
593
                }
594
595
596
                $response         = $this->lastResult = $this->unifyResponseFormat($responseDecoded);
597
598
                break;
599
600
            default: //Some goes wrong
601
                $this->lastCurlError = curl_error($this->curl);
602
                switch ($format) {
603
                    case 'json':
604
                        $response = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/',
605
                            function ($match) {
606
                            return mb_convert_encoding(pack('H*', $match[1]),
607
                                'UTF-8', 'UCS-2BE');
608
                        }, $this->lastCurlResponse);
609
                        $response = (json_encode(json_decode($response, true, 10),
610
                                JSON_PRETTY_PRINT));
611
                        break;
612
                    case 'xml':
613
                        if (strlen($this->lastCurlResponse)) {
614
                            $response = self::xml2array($this->lastCurlResponse);
615
                        }
616
                        break;
617
                }
618
619
                if (is_array($response)) {
620
                    $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...
621
                } elseif (strlen($response) && ($response != 'null')) {
622
                    $result = urldecode(http_build_query(self::object2array(current(json_decode($response)))));
623
                } else {
624
                    $result = null;
625
                }
626
627
                if ($response == 'null') {
628
                    if ($this->lastResponseCode == 200) {
629
                        $response = true;
630
                    } else {
631
                        $response = null;
632
                    }
633
                } else {
634
                    if (is_string($response)) {
635
                        $response = self::object2array(current(json_decode($response)));
636
                    }
637
                }
638
639
                if (is_array($response) && ($this->lastResponseCode == 400)) {
640
                    $this->logResult($response, $url);
641
                } else {
642
                    $this->addStatusMessage(sprintf('Error (HTTP %d): <pre>%s</pre> %s',
643
                            curl_getinfo($this->curl, CURLINFO_HTTP_CODE),
644
                            $result, $this->lastCurlError), 'error');
645
                    $this->addStatusMessage($url, 'info');
646
                    if (count($this->postFields)) {
647
                        if (is_array($result)) {
648
                            $this->addStatusMessage(urldecode(http_build_query($this->postFields)),
649
                                'debug');
650
                        } else {
651
                            $this->addStatusMessage(urldecode(http_build_query($this->getData())),
652
                                'debug');
653
                        }
654
                    }
655
                }
656
657
                break;
658
        }
659
660
        if ($this->debug === true) {
661
            $this->saveDebugFiles();
662
        }
663
664
        return $response;
665
    }
666
667
    /**
668
     * Vykonej HTTP požadavek
669
     *
670
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
671
     * @param string $url    URL požadavku
672
     * @param strinf $method HTTP Method GET|POST|PUT|OPTIONS|DELETE
673
     * @param string $format požadovaný formát komunikace
674
     * @return int HTTP Response CODE
675
     */
676
    public function doCurlRequest($url, $method, $format = null)
677
    {
678
        if (is_null($format)) {
679
            $format = $this->format;
680
        }
681
        curl_setopt($this->curl, CURLOPT_URL, $url);
682
// Nastavení samotné operace
683
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
684
//Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411
685
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
686
687
        $httpHeaders = $this->defaultHttpHeaders;
688
        switch ($format) {
689
            case 'json':
690
                $httpHeaders['Accept']       = 'application/json';
691
                $httpHeaders['Content-Type'] = 'application/json';
692
693
                break;
694
            case 'xml':
695
                $httpHeaders['Accept']       = 'application/xml';
696
                $httpHeaders['Content-Type'] = 'application/xml';
697
                break;
698
        }
699
700
        $httpHeadersFinal = [];
701
        foreach ($httpHeaders as $key => $value) {
702
            if (($key == 'User-Agent') && ($value == 'FlexiPeeHP')) {
703
                $value.= ' v'.self::$libVersion;
704
            }
705
            $httpHeadersFinal[] = $key.': '.$value;
706
        }
707
708
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
709
710
// Proveď samotnou operaci
711
        $this->lastCurlResponse = curl_exec($this->curl);
712
713
        $this->info = curl_getinfo($this->curl);
714
715
        $this->lastResponseCode = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
716
        return $this->lastResponseCode;
717
    }
718
719
    /**
720
     * Nastaví druh prováděné akce.
721
     *
722
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
723
     * @param string $action
724
     * @return boolean
725
     */
726
    public function setAction($action)
727
    {
728
        $result = false;
729
        if (is_null($this->actionsAvailable)) {
730
            $this->action = $action;
731
            $result       = true;
732
        } else {
733
            if (array_search($action, $this->actionsAvailable)) {
734
                $this->action = $action;
735
                $result       = true;
736
            }
737
        }
738
        return $result;
739
    }
740
741
    /**
742
     * Convert XML to array.
743
     *
744
     * @param string $xml
745
     *
746
     * @return array
747
     */
748
    public static function xml2array($xml)
749
    {
750
        $arr = [];
751
752
        if (is_string($xml)) {
753
            $xml = simplexml_load_string($xml);
754
        }
755
756
        foreach ($xml->children() as $r) {
757
            if (count($r->children()) == 0) {
758
                $arr[$r->getName()] = strval($r);
759
            } else {
760
                $arr[$r->getName()][] = self::xml2array($r);
761
            }
762
        }
763
764
        return $arr;
765
    }
766
767
    /**
768
     * Odpojení od FlexiBee.
769
     */
770
    public function disconnect()
771
    {
772
        if (is_resource($this->curl)) {
773
            curl_close($this->curl);
774
        }
775
        $this->curl = null;
776
    }
777
778
    public function __destruct()
779
    {
780
        $this->disconnect();
781
    }
782
783
    /**
784
     * Načte řádek dat z FlexiBee.
785
     *
786
     * @param int $recordID id požadovaného záznamu
787
     *
788
     * @return array
789
     */
790
    public function getFlexiRow($recordID)
791
    {
792
        $record   = null;
793
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
794
        if (isset($response[$this->evidence])) {
795
            $record = $response[$this->evidence][0];
796
        }
797
798
        return $record;
799
    }
800
801
    /**
802
     * Oddělí z pole podmínek ty jenž patří za ? v URL požadavku
803
     *
804
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
805
     * @param array $conditions pole podmínek   - rendrují se do ()
806
     * @param array $urlParams  pole parametrů  - rendrují za ?
807
     */
808
    public function extractUrlParams(&$conditions, &$urlParams)
809
    {
810
        foreach ($this->urlParams as $urlParam) {
811
            if (isset($conditions[$urlParam])) {
812
                \Ease\Sand::divDataArray($conditions, $urlParams, $urlParam);
813
            }
814
        }
815
    }
816
817
    /**
818
     * Načte data z FlexiBee.
819
     *
820
     * @param string $suffix     dotaz
821
     * @param string|array $conditions Volitelný filtrovací výraz
822
     */
823
    public function getFlexiData($suffix = null, $conditions = null)
824
    {
825
        $urlParams = $this->defaultUrlParams;
826
        if (!is_null($conditions)) {
827
            if (is_array($conditions)) {
828
                $this->extractUrlParams($conditions, $urlParams);
829
                $conditions = $this->flexiUrl($conditions);
830
            }
831
832
            if (strlen($conditions) && ($conditions[0] != '/')) {
833
                $conditions = '/'.rawurlencode('('.($conditions).')');
834
            }
835
        } else {
836
            $conditions = '';
837
        }
838
        if (strlen($suffix)) {
839
            $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.$suffix.'&'.http_build_query($urlParams),
840
                'GET');
841
        } else {
842
            $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.http_build_query($urlParams),
843
                'GET');
844
        }
845
        if (isset($transactions[$this->evidence])) {
846
            $result = $transactions[$this->evidence];
847
        } else {
848
            $result = $transactions;
849
        }
850
851
        return $result;
852
    }
853
854
    /**
855
     * Načte záznam z FlexiBee.
856
     *
857
     * @param int $id ID záznamu
858
     *
859
     * @return int počet načtených položek
860
     */
861 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...
862
    {
863
        $data = [];
864
        if (is_null($id)) {
865
            $id = $this->getMyKey();
866
        }
867
868
        $flexidata = $this->getFlexiData(null, '/'.$id);
869
        if (count($flexidata) == 1) {
870
            $data = current($flexidata);
871
        }
872
        return $this->takeData($data);
873
    }
874
875
    /**
876
     * Převede data do Json formátu pro FlexiBee.
877
     *
878
     * @param array $data
879
     *
880
     * @return string
881
     */
882
    public function jsonizeData($data)
883
    {
884
        $jsonize = [
885
            $this->nameSpace => [
886
                '@version' => $this->protoVersion,
887
                $this->evidence => $this->objectToID($data),
888
            ],
889
        ];
890
891
        if (!is_null($this->action)) {
892
            $jsonize[$this->nameSpace][$this->evidence.'@action'] = $this->action;
893
            $this->action                                         = null;
894
        }
895
896
        return json_encode($jsonize);
897
    }
898
899
    /**
900
     * Test if given record ID exists in FlexiBee.
901
     *
902
     * @param string|int $identifer
903
     */
904
    public function idExists($identifer = null)
905
    {
906
        if (is_null($identifer)) {
907
            $identifer = $this->getMyKey();
908
        }
909
        $flexiData = $this->getFlexiData(
910
            'detail=custom:'.$this->getmyKeyColumn(), $identifer);
911
912
        return $flexiData;
913
    }
914
915
    /**
916
     * Test if given record exists in FlexiBee.
917
     *
918
     * @param array $data
919
     * @return boolean Record presence status
920
     */
921
    public function recordExists($data = null)
922
    {
923
924
        if (is_null($data)) {
925
            $data = $this->getData();
926
        }
927
928
        $res = $this->getColumnsFromFlexibee([$this->myKeyColumn],
929
            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...
930
931
        if (!count($res) || (isset($res['success']) && ($res['success'] == 'false'))
932
            || !count($res[0])) {
933
            $found = false;
934
        } else {
935
            $found = true;
936
        }
937
        return $found;
938
    }
939
940
    /**
941
     * Vrací z FlexiBee sloupečky podle podmínek.
942
     *
943
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
944
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
945
     *                                     sloupečku
946
     * @return array
947
     */
948 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...
949
    {
950
        if (is_int($conditions)) {
951
            $conditions = [$this->getmyKeyColumn() => $conditions];
952
        }
953
954
        $flexiData = $this->getFlexiData('', $conditions);
955
956
        if (!is_null($indexBy)) {
957
            $flexiData = $this->reindexArrayBy($flexiData);
958
        }
959
960
        return $flexiData;
961
    }
962
963
    /**
964
     * Vrací z FlexiBee sloupečky podle podmínek.
965
     *
966
     * @param string[] $columnsList seznam položek
967
     * @param array    $conditions  pole podmínek nebo ID záznamu
968
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
969
     *
970
     * @return array
971
     */
972
    public function getColumnsFromFlexibee($columnsList, $conditions = null,
973
                                           $indexBy = null)
974
    {
975
        $detail = 'full';
976
977
        if (is_int($conditions)) {
978
            $conditions = [$this->getmyKeyColumn() => $conditions];
979
        }
980
981
        if ($columnsList != '*') {
982
            if (is_array($columnsList)) {
983
                if (!is_null($indexBy) && !array_key_exists($indexBy,
984
                        $columnsList)) {
985
                    $columnsList[] = $indexBy;
986
                }
987
                $columns = implode(',', array_unique($columnsList));
988
            } else {
989
                $columns = $columnsList;
990
            }
991
            $detail = 'custom:'.$columns;
992
        }
993
994
        $flexiData = $this->getFlexiData('detail='.$detail, $conditions);
995
996
        if (!is_null($indexBy) && count($flexiData) && count(current($flexiData))) {
997
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
998
        }
999
1000
        return $flexiData;
1001
    }
1002
1003
    /**
1004
     * Vrací kód záznamu.
1005
     *
1006
     * @param mixed $data
1007
     *
1008
     * @return string
1009
     */
1010
    public function getKod($data = null, $unique = true)
1011
    {
1012
        $kod = null;
1013
1014
        if (is_null($data)) {
1015
            $data = $this->getData();
1016
        }
1017
1018
        if (is_string($data)) {
1019
            $data = [$this->nameColumn => $data];
1020
        }
1021
1022
        if (isset($data['kod'])) {
1023
            $kod = $data['kod'];
1024
        } else {
1025
            if (isset($data[$this->nameColumn])) {
1026
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
1027
                    \Ease\Sand::rip($data[$this->nameColumn]));
1028
            } else {
1029
                if (isset($data[$this->myKeyColumn])) {
1030
                    $kod = \Ease\Sand::rip($data[$this->myKeyColumn]);
1031
                }
1032
            }
1033
        }
1034
1035
        if (!strlen($kod)) {
1036
            $kod = 'NOTSET';
1037
        }
1038
1039
        if (strlen($kod) > 18) {
1040
            $kodfinal = strtoupper(substr($kod, 0, 18));
1041
        } else {
1042
            $kodfinal = strtoupper($kod);
1043
        }
1044
1045
        if ($unique) {
1046
            $counter = 0;
1047
            if (count($this->codes)) {
1048
                foreach ($this->codes as $codesearch => $keystring) {
1049
                    if (strstr($codesearch, $kodfinal)) {
1050
                        ++$counter;
1051
                    }
1052
                }
1053
            }
1054
            if ($counter) {
1055
                $kodfinal = $kodfinal.$counter;
1056
            }
1057
1058
            $this->codes[$kodfinal] = $kod;
1059
        }
1060
1061
        return $kodfinal;
1062
    }
1063
1064
    /**
1065
     * Write Operation Result.
1066
     *
1067
     * @param array  $resultData
1068
     * @param string $url        URL
1069
     * @return boolean Log save success
1070
     */
1071
    public function logResult($resultData = null, $url = null)
1072
    {
1073
        $logResult = false;
1074
        if (isset($resultData['success']) && ($resultData['success'] == 'false')) {
1075
            if (isset($resultData['message'])) {
1076
                $this->addStatusMessage($resultData['message'], 'warning');
1077
            }
1078
            $this->addStatusMessage('Error '.$this->lastResponseCode.': '.urldecode($url),
1079
                'warning');
1080
            unset($url);
1081
        }
1082
        if (is_null($resultData)) {
1083
            $resultData = $this->lastResult;
1084
        }
1085
        if (isset($url)) {
1086
            $this->logger->addStatusMessage(urldecode($url));
1087
        }
1088
1089
        if (isset($resultData['results'])) {
1090
            $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...
1091
            if ($resultData['success'] == 'false') {
1092
                $status = 'error';
1093
            } else {
1094
                $status = 'success';
1095
            }
1096
            foreach ($resultData['results'] as $result) {
1097
                if (isset($result['request-id'])) {
1098
                    $rid = $result['request-id'];
1099
                } else {
1100
                    $rid = '';
1101
                }
1102
                if (isset($result['errors'])) {
1103
                    foreach ($result['errors'] as $error) {
1104
                        $message = $error['message'];
1105
                        if (isset($error['for'])) {
1106
                            $message .= ' for: '.$error['for'];
1107
                        }
1108
                        if (isset($error['value'])) {
1109
                            $message .= ' value:'.$error['value'];
1110
                        }
1111
                        if (isset($error['code'])) {
1112
                            $message .= ' code:'.$error['code'];
1113
                        }
1114
                        $this->addStatusMessage($rid.': '.$message, $status);
1115
                    }
1116
                }
1117
            }
1118
        }
1119
1120
        if (is_object($this->logger)) {
1121
            $logResult = $this->logger->flush(get_class($this));
1122
        }
1123
        return $logResult;
1124
    }
1125
1126
    /**
1127
     * Save RAW Curl Request & Response to files in Temp directory
1128
     */
1129
    public function saveDebugFiles()
1130
    {
1131
        $tmpdir = sys_get_temp_dir();
1132
        file_put_contents($tmpdir.'/request-'.$this->evidence.'-'.microtime().'.'.$this->format,
1133
            $this->postFields);
1134
        file_put_contents($tmpdir.'/response-'.$this->evidence.'-'.microtime().'.'.$this->format,
1135
            $this->lastCurlResponse);
1136
    }
1137
1138
    /**
1139
     * Připraví data pro odeslání do FlexiBee
1140
     * 
1141
     * @param string $data
1142
     */
1143
    public function setPostFields($data)
1144
    {
1145
        $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...
1146
    }
1147
1148
    /**
1149
     * Generuje fragment url pro filtrování.
1150
     *
1151
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
1152
     *
1153
     * @param array  $data
1154
     * @param string $joiner default and/or
1155
     * @param string $defop  default operator
1156
     *
1157
     * @return string
1158
     */
1159
    public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq')
1160
    {
1161
        $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...
1162
        $parts    = [];
1163
1164
        foreach ($data as $column => $value) {
1165
            if (is_integer($data[$column]) || is_float($data[$column])) {
1166
                $parts[$column] = $column.' eq \''.$data[$column].'\'';
1167
            } elseif (is_bool($data[$column])) {
1168
                $parts[$column] = $data[$column] ? $column.' eq true' : $column.' eq false';
1169
            } elseif (is_null($data[$column])) {
1170
                $parts[$column] = $column." is null";
1171
            } else {
1172
                switch ($value) {
1173
                    case '!null':
1174
                        $parts[$column] = $column." is not null";
1175
                        break;
1176
                    case 'is empty':
1177
                    case 'is not empty':
1178
                        $parts[$column] = $column.' '.$value;
1179
                        break;
1180
                    default:
1181
                        $parts[$column] = $column." $defop '".$data[$column]."'";
1182
                        break;
1183
                }
1184
            }
1185
        }
1186
1187
        $flexiUrl = implode(' '.$joiner.' ', $parts);
1188
1189
        return $flexiUrl;
1190
    }
1191
1192
    /**
1193
     * Vrací identifikátor objektu code: nebo id:
1194
     *
1195
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1196
     * @return string indentifikátor záznamu reprezentovaného objektem
1197
     */
1198
    public function __toString()
1199
    {
1200
        $myCode = $this->getDataValue('kod');
1201
        if ($myCode) {
1202
            $id = 'code:'.$myCode;
1203
        } else {
1204
            $id = $this->getDataValue('id');
1205
            if (is_null($id)) {
1206
                $this->addToLog('Object Data does not contain code: or id: cannot match with statement!',
1207
                    'warning');
1208
            }
1209
        }
1210
        return $id;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $id; (object|integer|double|string|array|boolean|null) is incompatible with the return type of the parent method Ease\Sand::__toString of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
1211
    }
1212
1213
    /**
1214
     * Gives you FlexiPeeHP class name for Given Evidence
1215
     *
1216
     * @param string $evidence
1217
     * @return string Class name
1218
     */
1219
    static public function evidenceToClassName($evidence)
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
1220
    {
1221
        return str_replace(' ', '', ucwords(str_replace('-', ' ', $evidence)));
1222
    }
1223
1224
    /**
1225
     * Vrací hodnotu daného externího ID
1226
     *
1227
     * @param string $want Which ? If empty,you obtain the first one.
1228
     * @return string
1229
     */
1230
    public function getExternalID($want = null)
1231
    {
1232
        $extid = null;
1233
        $ids   = $this->getDataValue('external-ids');
1234
        if (is_null($want)) {
1235
            if (count($ids)) {
1236
                $extid = current($ids);
1237
            }
1238
        } else {
1239
            if (!is_null($ids)) {
1240
                foreach ($ids as $id) {
0 ignored issues
show
Bug introduced by
The expression $ids of type object|integer|double|string|array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1241
                    if (strstr($id, 'ext:'.$want)) {
1242
                        $extid = str_replace('ext:'.$want.':', '', $id);
1243
                    }
1244
                }
1245
            }
1246
        }
1247
        return $extid;
1248
    }
1249
1250
    /**
1251
     * Obtain actual GlobalVersion
1252
     * Vrací aktuální globální verzi změn
1253
     *
1254
     * @link https://www.flexibee.eu/api/dokumentace/ref/changes-api#globalVersion Globální Verze
1255
     * @return type
1256
     */
1257
    public function getGlobalVersion()
1258
    {
1259
        $globalVersion = null;
1260
        if (!count($this->lastResult) || !isset($this->lastResult['@globalVersion'])) {
1261
            $this->getFlexiData(null,
1262
                ['add-global-version' => 'true', 'limit' => 1]);
1263
        }
1264
1265
        if (isset($this->lastResult['@globalVersion'])) {
1266
            $globalVersion = intval($this->lastResult['@globalVersion']);
1267
        }
1268
1269
        return $globalVersion;
1270
    }
1271
1272
    /**
1273
     * Return the same response format for one and multiplete results
1274
     * 
1275
     * @param array $responseRaw
1276
     * @return array
1277
     */
1278
    public function unifyResponseFormat($responseRaw)
1279
    {
1280
        $response = null;
1281
        $evidence = $this->getResponseEvidence();
1282
        if (is_array($responseRaw)) {
1283
            // Get response body root automatically
1284
            if (array_key_exists($this->nameSpace, $responseRaw)) { //Unifi response format
1285
                $responseBody = $responseRaw[$this->nameSpace];
1286
                if (array_key_exists($evidence, $responseBody)) {
1287
                    $evidenceContent = $responseBody[$evidence];
1288
                    if (array_key_exists(0, $evidenceContent)) {
1289
                        $response[$evidence] = $evidenceContent; //Multiplete Results
1290
                    } else {
1291
                        $response[$evidence][0] = $evidenceContent; //One result
1292
                    }
1293
                } else {
1294
                    $response = $responseBody;
1295
                }
1296
            } else {
1297
                $response = $responseRaw;
1298
            }
1299
        }
1300
        return $response;
1301
    }
1302
1303
    /**
1304
     * Obtain structure for current (or given) evidence
1305
     *
1306
     * @param string $evidence
1307
     * @return array Evidence structure
1308
     */
1309 View Code Duplication
    public function getColumnsInfo($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...
1310
    {
1311
        $columnsInfo = null;
1312
        if (is_null($evidence)) {
1313
            $evidence = $this->getEvidence();
1314
        }
1315
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1316
        if (isset(\FlexiPeeHP\Properties::$$propsName)) {
1317
            $columnsInfo = Properties::$$propsName;
1318
        }
1319
        return $columnsInfo;
1320
    }
1321
1322
    /**
1323
     * Obtain actions for current (or given) evidence
1324
     *
1325
     * @param string $evidence
1326
     * @return array Evidence structure
1327
     */
1328 View Code Duplication
    public function getActionsInfo($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...
1329
    {
1330
        $actionsInfo = null;
1331
        if (is_null($evidence)) {
1332
            $evidence = $this->getEvidence();
1333
        }
1334
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1335
        if (isset(\FlexiPeeHP\Actions::$$propsName)) {
1336
            $actionsInfo = Actions::$$propsName;
1337
        }
1338
        return $actionsInfo;
1339
    }
1340
1341
    /**
1342
     * Obtain relations for current (or given) evidence
1343
     *
1344
     * @param string $evidence
1345
     * @return array Evidence structure
1346
     */
1347
    public function getRelationsInfo($evidence = null)
1348
    {
1349
        $relationsInfo = null;
1350
        if (is_null($evidence)) {
1351
            $evidence = $this->getEvidence();
1352
        }
1353
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1354
        if (isset(\FlexiPeeHP\Relations::$$propsName)) {
1355
            $relationsInfo = Relations::$$propsName;
1356
        }
1357
        return $relationsInfo;
1358
    }
1359
1360
    /**
1361
     * Obtain info for current (or given) evidence
1362
     *
1363
     * @param string $evidence
1364
     * @return array Evidence info
1365
     */
1366 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...
1367
    {
1368
        $evidencesInfo = null;
1369
        if (is_null($evidence)) {
1370
            $evidence = $this->getEvidence();
1371
        }
1372
        if (isset(EvidenceList::$evidences[$evidence])) {
1373
            $evidencesInfo = EvidenceList::$evidences[$evidence];
1374
        }
1375
        return $evidencesInfo;
1376
    }
1377
1378
    /**
1379
     * Obtain name for current (or given) evidence path
1380
     *
1381
     * @param string $evidence Evidence Path
1382
     * @return array Evidence info
1383
     */
1384 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...
1385
    {
1386
        $evidenceName = null;
1387
        if (is_null($evidence)) {
1388
            $evidence = $this->getEvidence();
1389
        }
1390
        if (isset(EvidenceList::$name[$evidence])) {
1391
            $evidenceName = EvidenceList::$name[$evidence];
1392
        }
1393
        return $evidenceName;
1394
    }
1395
1396
    /**
1397
     * Perform given action (if availble) on current evidence/record
1398
     * @url https://demo.flexibee.eu/devdoc/actions
1399
     * 
1400
     * @param string $action one of evidence actions
1401
     * @param string $method ext|int External method call operation in URL.
1402
     *                               Internal add the @action element to request body
1403
     */
1404
    public function performAction($action, $method = 'ext')
1405
    {
1406
        $result = null;
0 ignored issues
show
Unused Code introduced by
$result 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...
1407
        if (is_null($this->actionsAvailable)) {
1408
            $this->actionsAvailble = $this->getActionsInfo();
0 ignored issues
show
Bug introduced by
The property actionsAvailble does not seem to exist. Did you mean action?

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...
1409
        }
1410
1411
        if (is_array($this->actionsAvailble) && array_key_exists($action,
0 ignored issues
show
Bug introduced by
The property actionsAvailble does not seem to exist. Did you mean action?

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...
1412
                $this->actionsAvailble)) {
0 ignored issues
show
Bug introduced by
The property actionsAvailble does not seem to exist. Did you mean action?

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...
1413
            switch ($this->actionsAvailble[$action]['actionMakesSense']) {
0 ignored issues
show
Bug introduced by
The property actionsAvailble does not seem to exist. Did you mean action?

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...
1414
                case 'ONLY_WITH_INSTANCE_AND_NOT_IN_EDIT':
1415
                case 'ONLY_WITH_INSTANCE': //Add instance
1416
                    $urlSuffix = '/'.$this->__toString().'/'.$action.'.'.$this->format;
1417
                    break;
1418
1419
                default:
1420
                    $urlSuffix = '/'.$action;
1421
                    break;
1422
            }
1423
1424
            switch ($method) {
1425
                case 'int':
1426
                    $this->setAction($action);
1427
                    $result = $this->performRequest(null, 'POST');
1428
                    break;
1429
1430
                default:
1431
                    $result = $this->performRequest($urlSuffix, 'GET');
1432
                    break;
1433
            }
1434
        } else {
1435
            throw new \Exception(sprintf(_('Unsupported action %s for evidence %s'),
1436
                $action, $this->getEvidence()));
1437
        }
1438
1439
        return $result;
1440
    }
1441
}
1442