Completed
Push — master ( 1ef83c...516478 )
by Vítězslav
13:51
created

FlexiBeeRO::getColumnsInfo()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 12
Ratio 100 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 4
nop 1
dl 12
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
class FlexiBeeRO extends \Ease\Brick
12
{
13
    /**
14
     * Základní namespace pro komunikaci s FlexiBee.
15
     * Basic namespace for communication with FlexiBee
16
     *
17
     * @var string Jmený prostor datového bloku odpovědi
18
     */
19
    public $nameSpace = 'winstrom';
20
21
    /**
22
     * Datový blok v poli odpovědi.
23
     * Data block in response field.
24
     *
25
     * @var string
26
     */
27
    public $resultField = 'results';
28
29
    /**
30
     * Verze protokolu použitého pro komunikaci.
31
     * Communication protocol version used.
32
     *
33
     * @var string Verze použitého API
34
     */
35
    public $protoVersion = '1.0';
36
37
    /**
38
     * Evidence užitá objektem.
39
     * Evidence used by object
40
     *
41
     * @link https://demo.flexibee.eu/c/demo/evidence-list Přehled evidencí
42
     * @var string
43
     */
44
    public $evidence = null;
45
46
    /**
47
     * Výchozí formát pro komunikaci.
48
     * Default communication format.
49
     *
50
     * @link https://www.flexibee.eu/api/dokumentace/ref/format-types Přehled možných formátů
51
     *
52
     * @var string json|xml|...
53
     */
54
    public $format = 'json';
55
56
    /**
57
     * Curl Handle.
58
     *
59
     * @var resource
60
     */
61
    public $curl = null;
62
63
    /**
64
     * @link https://demo.flexibee.eu/devdoc/company-identifier Identifikátor firmy
65
     * @var string
66
     */
67
    public $company = null;
68
69
    /**
70
     * Server[:port]
71
     * @var string
72
     */
73
    public $url = null;
74
75
    /**
76
     * REST API Username
77
     * @var string
78
     */
79
    public $user = null;
80
81
    /**
82
     * REST API Password
83
     * @var string
84
     */
85
    public $password = null;
86
87
    /**
88
     * @var array Pole HTTP hlaviček odesílaných s každým požadavkem
89
     */
90
    public $defaultHttpHeaders = ['User-Agent' => 'FlexiPeeHP v1.6'];
91
92
    /**
93
     * Default additional request url parameters after question mark
94
     * 
95
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls   Common params
96
     * @link https://www.flexibee.eu/api/dokumentace/ref/paging Paging params
97
     * @var array
98
     */
99
    public $defaultUrlParams = ['limit' => 0];
100
101
    /**
102
     * Identifikační řetězec.
103
     *
104
     * @var string
105
     */
106
    public $init = null;
107
108
    /**
109
     * Sloupeček s názvem.
110
     *
111
     * @var string
112
     */
113
    public $nameColumn = 'nazev';
114
115
    /**
116
     * Sloupeček obsahující datum vložení záznamu do shopu.
117
     *
118
     * @var string
119
     */
120
    public $myCreateColumn = 'false';
121
122
    /**
123
     * Slopecek obsahujici datum poslení modifikace záznamu do shopu.
124
     *
125
     * @var string
126
     */
127
    public $myLastModifiedColumn = 'lastUpdate';
128
129
    /**
130
     * Klíčový idendifikátor záznamu.
131
     *
132
     * @var string
133
     */
134
    public $fbKeyColumn = 'id';
135
136
    /**
137
     * Informace o posledním HTTP requestu.
138
     *
139
     * @var *
140
     */
141
    public $info;
142
143
    /**
144
     * Informace o poslední HTTP chybě.
145
     *
146
     * @var string
147
     */
148
    public $lastCurlError = null;
149
150
    /**
151
     * Used codes storage.
152
     *
153
     * @var array
154
     */
155
    public $codes = null;
156
157
    /**
158
     * Last Inserted ID.
159
     *
160
     * @var int
161
     */
162
    public $lastInsertedID = null;
163
164
    /**
165
     * Default Line Prefix.
166
     *
167
     * @var string
168
     */
169
    public $prefix = '/c/';
170
171
    /**
172
     * Raw Content of last curl response
173
     * 
174
     * @var string
175
     */
176
    public $lastCurlResponse;
177
178
    /**
179
     * HTTP Response code of last request
180
     *
181
     * @var int
182
     */
183
    public $lastResponseCode = null;
184
185
    /**
186
     * Array of fields for next curl POST operation
187
     *
188
     * @var array
189
     */
190
    protected $postFields = [];
191
192
    /**
193
     * Last operation result data or message(s)
194
     *
195
     * @var array
196
     */
197
    public $lastResult = null;
198
199
    /**
200
     * Nuber from  @rowCount
201
     * @var int
202
     */
203
    public $rowCount = null;
204
205
    /**
206
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
207
     * @var string
208
     */
209
    protected $action;
210
211
    /**
212
     * Pole akcí které podporuje ta která evidence
213
     * @link https://demo.flexibee.eu/c/demo/faktura-vydana/actions.json Např. Akce faktury
214
     * @var array
215
     */
216
    public $actionsAvailable = null;
217
218
    /**
219
     * Parmetry pro URL
220
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Všechny podporované parametry
221
     * @var array
222
     */
223
    public $urlParams = [
224
        'dry-run',
225
        'fail-on-warning',
226
        'report-name',
227
        'report-lang',
228
        'report-sign',
229
        'detail',
230
        'mode',
231
        'limit',
232
        'start',
233
        'order',
234
        'sort',
235
        'add-row-count',
236
        'relations',
237
        'includes',
238
        'use-ext-id',
239
        'use-internal-id',
240
        'stitky-as-ids',
241
        'only-ext-ids',
242
        'no-ext-ids',
243
        'no-ids',
244
        'code-as-id',
245
        'no-http-errors',
246
        'export-settings',
247
        'as-gui',
248
        'code-in-response',
249
        'add-global-version',
250
        'encoding',
251
        'delimeter',
252
        'format',
253
        'auth',
254
        'skupina-stitku',
255
        'dir',
256
        'xpath', // See: https://www.flexibee.eu/api/dokumentace/ref/xpath/
257
        'dry-run', // See: https://www.flexibee.eu/api/dokumentace/ref/dry-run/
258
        'inDesktopApp' // Note: Undocumented function (html only)
259
    ];
260
261
    /**
262
     * Class for read only interaction with FlexiBee.
263
     *
264
     * @param mixed $init default record id or initial data
265
     * @param array $options Connection settings override
266
     */
267
    public function __construct($init = null, $options = [])
268
    {
269
        $this->init = $init;
270
271
        parent::__construct();
272
        $this->setUp($options);
273
        $this->curlInit();
274
        if (!is_null($init)) {
275
            $this->processInit($init);
276
        }
277
    }
278
279
    /**
280
     * SetUp Object to be ready for connect
281
     *
282
     * @param array $options Object Options
283
     */
284
    public function setUp($options = [])
285
    {
286 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...
287
            $this->company = $options['company'];
288
        } else {
289
            if (is_null($this->company) && defined('FLEXIBEE_COMPANY')) {
290
                $this->company = constant('FLEXIBEE_COMPANY');
291
            }
292
        }
293 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...
294
            $this->url = $options['url'];
295
        } else {
296
            if (is_null($this->url) && defined('FLEXIBEE_URL')) {
297
                $this->url = constant('FLEXIBEE_URL');
298
            }
299
        }
300 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...
301
            $this->user = $options['user'];
302
        } else {
303
            if (is_null($this->user) && defined('FLEXIBEE_LOGIN')) {
304
                $this->user = constant('FLEXIBEE_LOGIN');
305
            }
306
        }
307 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...
308
            $this->password = $options['password'];
309
        } else {
310
            if (is_null($this->password) && defined('FLEXIBEE_PASSWORD')) {
311
                $this->password = constant('FLEXIBEE_PASSWORD');
312
            }
313
        }
314
        if (isset($options['evidence'])) {
315
            $this->setEvidence($options['evidence']);
316
        }
317
        if (isset($options['prefix'])) {
318
            $this->setPrefix($options['prefix']);
319
        }
320
    }
321
322
    /**
323
     * Inicializace CURL
324
     */
325
    public function curlInit()
326
    {
327
        $this->curl = \curl_init(); // create curl resource
328
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); // return content as a string from curl_exec
329
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true); // follow redirects (compatibility for future changes in FlexiBee)
330
        curl_setopt($this->curl, CURLOPT_HTTPAUTH, true);       // HTTP authentication
331
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); // FlexiBee by default uses Self-Signed certificates
332
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
333
        curl_setopt($this->curl, CURLOPT_VERBOSE, true); // For debugging
334
        curl_setopt($this->curl, CURLOPT_USERPWD,
335
            $this->user.':'.$this->password); // set username and password
336
    }
337
338
    /**
339
     * Zinicializuje objekt dle daných dat
340
     * 
341
     * @param mixed $init
342
     */
343
    public function processInit($init)
344
    {
345
        if (is_integer($init)) {
346
            $this->loadFromFlexiBee($init);
347
        } elseif (is_array($init)) {
348
            $this->takeData($init);
349
        } elseif (strstr($init, 'code:')) {
350
            $this->loadFromFlexiBee($init);
351
        }
352
    }
353
354
    /**
355
     * Set URL prefix
356
     *
357
     * @param string $prefix
358
     */
359
    public function setPrefix($prefix)
360
    {
361
        switch ($prefix) {
362
            case 'a': //Access
363
            case 'c': //Company
364
            case 'u': //User
365
            case 'g': //License Groups
366
            case 'admin':
367
            case 'status':
368
            case 'login-logout':
369
                $this->prefix = '/'.$prefix.'/';
370
                break;
371
            case null:
372
            case '':
373
            case '/':
374
                $this->prefix = '';
375
                break;
376
            default:
377
                throw new \Exception(sprintf('Unknown prefix %s', $prefix));
378
                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...
379
        }
380
    }
381
382
    /**
383
     * Nastaví Evidenci pro Komunikaci.
384
     * Set evidence for communication
385
     *
386
     * @param string $evidence evidence pathName to use
387
     * @return boolean evidence switching status
388
     */
389
    public function setEvidence($evidence)
390
    {
391
        $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...
392
        switch ($this->prefix) {
393
            case '/c/':
394
                if (array_key_exists($evidence, EvidenceList::$name)) {
395
                    $this->evidence = $evidence;
396
                    $result         = true;
397
                } else {
398
                    throw new \Exception(sprintf('Try to set unsupported evidence %s',
399
                        $evidence));
400
                }
401
                break;
402
            default:
403
                $this->evidence = $evidence;
404
                $result         = true;
405
                break;
406
        }
407
        return $result;
408
    }
409
410
    /**
411
     * Vrací právě používanou evidenci pro komunikaci
412
     * Obtain current used evidence
413
     *
414
     * @return string
415
     */
416
    public function getEvidence()
417
    {
418
        return $this->evidence;
419
    }
420
421
    /**
422
     * Set used company.
423
     * Nastaví Firmu.
424
     *
425
     * @param string $company
426
     */
427
    public function setCompany($company)
428
    {
429
        $this->company = $company;
430
    }
431
432
    /**
433
     * Obtain company now used
434
     * Vrací právě používanou firmu
435
     *
436
     * @return string
437
     */
438
    public function getCompany()
439
    {
440
        return $this->company;
441
    }
442
443
    /**
444
     * Vrací název evidence použité v odpovědích z FlexiBee
445
     *
446
     * @return string
447
     */
448
    public function getResponseEvidence()
449
    {
450
        switch ($this->evidence) {
451
            case 'c':
452
                $evidence = 'companies';
453
                break;
454
            default:
455
                $evidence = $this->getEvidence();
456
                break;
457
        }
458
        return $evidence;
459
    }
460
461
    /**
462
     * Převede rekurzivně Objekt na pole.
463
     *
464
     * @param object|array $object
465
     *
466
     * @return array
467
     */
468
    public static function object2array($object)
469
    {
470
        $result = null;
471
        if (is_object($object)) {
472
            $objectData = get_object_vars($object);
473
            if (is_array($objectData) && count($objectData)) {
474
                $result = array_map('self::object2array', $objectData);
475
            }
476 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...
477
            if (is_array($object)) {
478
                foreach ($object as $item => $value) {
479
                    $result[$item] = self::object2array($value);
480
                }
481
            } else {
482
                $result = $object;
483
            }
484
        }
485
486
        return $result;
487
    }
488
489
    /**
490
     * Převede rekurzivně v poli všechny objekty na jejich identifikátory.
491
     *
492
     * @param object|array $object
493
     *
494
     * @return array
495
     */
496
    public static function objectToID($object)
497
    {
498
        $result = null;
499
        if (is_object($object)) {
500
            $result = $object->__toString();
501 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...
502
            if (is_array($object)) {
503
                foreach ($object as $item => $value) {
504
                    $result[$item] = self::objectToID($value);
505
                }
506
            } else { //String
507
                $result = $object;
508
            }
509
        }
510
511
        return $result;
512
    }
513
514
    /**
515
     * Return basic URL for used Evidence
516
     *
517
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
518
     * @param string $urlSuffix
519
     */
520
    public function getEvidenceURL($urlSuffix = null)
521
    {
522
        if (is_null($urlSuffix)) {
523
            $urlSuffix = $this->getEvidence();
524
        } elseif ($urlSuffix[0] == ';') {
525
            $urlSuffix = $this->getEvidence().$urlSuffix;
526
        }
527
        return $this->url.$this->prefix.$this->company.'/'.$urlSuffix;
528
    }
529
530
    /**
531
     * Funkce, která provede I/O operaci a vyhodnotí výsledek.
532
     *
533
     * @param string $urlSuffix část URL za identifikátorem firmy.
534
     * @param string $method    HTTP/REST metoda
535
     * @param string $format    Requested format
536
     * @return array|boolean Výsledek operace
537
     */
538
    public function performRequest($urlSuffix = null, $method = 'GET',
539
                                   $format = null)
540
    {
541
        $this->rowCount = null;
542
        $url            = $this->getEvidenceURL($urlSuffix);
543
544
        $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...
545
546
        if (is_null($format)) {
547
            $format = $this->format;
548
        }
549
550
        switch ($responseCode) {
551
            case 200:
552
            case 201:
553
                // Parse response
554
                $responseDecoded = [];
555
556
                switch ($format) {
557
                    case 'json':
558
                        $responseDecoded = json_decode($this->lastCurlResponse,
559
                            true, 10);
560
                        if (($method == 'PUT') && isset($responseDecoded[$this->nameSpace][$this->resultField][0]['id'])) {
561
                            $this->lastInsertedID = $responseDecoded[$this->nameSpace][$this->resultField][0]['id'];
562
                            $this->setMyKey($this->lastInsertedID);
563
                        } else {
564
                            $this->lastInsertedID = null;
565
                            if (isset($responseDecoded[$this->nameSpace]['@rowCount'])) {
566
                                $this->rowCount = (int) $responseDecoded[$this->nameSpace]['@rowCount'];
567
                            }
568
                        }
569
                        $decodeError = json_last_error_msg();
570
                        if ($decodeError != 'No error') {
571
                            $this->addStatusMessage($decodeError, 'error');
572
                        }
573
                        break;
574
                    case 'xml':
575
                        if (strlen($this->lastCurlResponse)) {
576
                            $responseDecoded = self::xml2array($this->lastCurlResponse);
577
                        } else {
578
                            $responseDecoded = null;
579
                        }
580
                        break;
581
                }
582
583
584
                $response         = $this->lastResult = $this->unifyResponseFormat($responseDecoded);
585
586
                break;
587
588
            default: //Some goes wrong
589
                $this->lastCurlError = curl_error($this->curl);
590
                switch ($format) {
591
                    case 'json':
592
                        $response = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/',
593
                            function ($match) {
594
                            return mb_convert_encoding(pack('H*', $match[1]),
595
                                'UTF-8', 'UCS-2BE');
596
                        }, $this->lastCurlResponse);
597
                        $response = (json_encode(json_decode($response, true, 10),
598
                                JSON_PRETTY_PRINT));
599
                        break;
600
                    case 'xml':
601
                        if (strlen($this->lastCurlResponse)) {
602
                            $response = self::xml2array($this->lastCurlResponse);
603
                        }
604
                        break;
605
                }
606
607
                if (is_array($response)) {
608
                    $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...
609
                } elseif (strlen($response) && ($response != 'null')) {
610
                    $result = urldecode(http_build_query(self::object2array(current(json_decode($response)))));
611
                } else {
612
                    $result = null;
613
                }
614
615
                if ($response == 'null') {
616
                    if ($this->lastResponseCode == 200) {
617
                        $response = true;
618
                    } else {
619
                        $response = null;
620
                    }
621
                } else {
622
                    if (is_string($response)) {
623
                        $response = self::object2array(current(json_decode($response)));
624
                    }
625
                }
626
627
                if (is_array($response) && ($this->lastResponseCode == 400)) {
628
                    $this->logResult($response, $url);
629
                } else {
630
                    $this->addStatusMessage(sprintf('Error (HTTP %d): <pre>%s</pre> %s',
631
                            curl_getinfo($this->curl, CURLINFO_HTTP_CODE),
632
                            $result, $this->lastCurlError), 'error');
633
                    $this->addStatusMessage($url, 'info');
634
                    if (count($this->postFields)) {
635
                        if (is_array($result)) {
636
                            $this->addStatusMessage(urldecode(http_build_query($this->postFields)),
637
                                'debug');
638
                        } else {
639
                            $this->addStatusMessage(urldecode(http_build_query($this->getData())),
640
                                'debug');
641
                        }
642
                    }
643
                }
644
645
                break;
646
        }
647
        return $response;
648
    }
649
650
    /**
651
     * Vykonej HTTP požadavek
652
     *
653
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
654
     * @param string $url    URL požadavku
655
     * @param strinf $method HTTP Method GET|POST|PUT|OPTIONS|DELETE
656
     * @param string $format požadovaný formát komunikace
657
     * @return int HTTP Response CODE
658
     */
659
    public function doCurlRequest($url, $method, $format = null)
660
    {
661
        if (is_null($format)) {
662
            $format = $this->format;
663
        }
664
        curl_setopt($this->curl, CURLOPT_URL, $url);
665
// Nastavení samotné operace
666
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
667
//Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411
668
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
669
670
        $httpHeaders = $this->defaultHttpHeaders;
671
        switch ($format) {
672
            case 'json':
673
                $httpHeaders['Accept']       = 'application/json';
674
                $httpHeaders['Content-Type'] = 'application/json';
675
676
                break;
677
            case 'xml':
678
                $httpHeaders['Accept']       = 'application/xml';
679
                $httpHeaders['Content-Type'] = 'application/xml';
680
                break;
681
        }
682
683
        $httpHeadersFinal = [];
684
        foreach ($httpHeaders as $key => $value) {
685
            $httpHeadersFinal[] = $key.': '.$value;
686
        }
687
688
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
689
690
// Proveď samotnou operaci
691
        $this->lastCurlResponse = curl_exec($this->curl);
692
693
        $this->info = curl_getinfo($this->curl);
694
695
        $this->lastResponseCode = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
696
        return $this->lastResponseCode;
697
    }
698
699
    /**
700
     * Nastaví druh prováděné akce.
701
     *
702
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
703
     * @param string $action
704
     * @return boolean
705
     */
706
    public function setAction($action)
707
    {
708
        $result = false;
709
        if (is_null($this->actionsAvailable)) {
710
            $this->action = $action;
711
            $result       = true;
712
        } else {
713
            if (array_search($action, $this->actionsAvailable)) {
714
                $this->action = $action;
715
                $result       = true;
716
            }
717
        }
718
        return $result;
719
    }
720
721
    /**
722
     * Convert XML to array.
723
     *
724
     * @param string $xml
725
     *
726
     * @return array
727
     */
728
    public static function xml2array($xml)
729
    {
730
        $arr = [];
731
732
        if (is_string($xml)) {
733
            $xml = simplexml_load_string($xml);
734
        }
735
736
        foreach ($xml->children() as $r) {
737
            if (count($r->children()) == 0) {
738
                $arr[$r->getName()] = strval($r);
739
            } else {
740
                $arr[$r->getName()][] = self::xml2array($r);
741
            }
742
        }
743
744
        return $arr;
745
    }
746
747
    /**
748
     * Odpojení od FlexiBee.
749
     */
750
    public function disconnect()
751
    {
752
        if (is_resource($this->curl)) {
753
            curl_close($this->curl);
754
        }
755
        $this->curl = null;
756
    }
757
758
    public function __destruct()
759
    {
760
        $this->disconnect();
761
    }
762
763
    /**
764
     * Načte řádek dat z FlexiBee.
765
     *
766
     * @param int $recordID id požadovaného záznamu
767
     *
768
     * @return array
769
     */
770
    public function getFlexiRow($recordID)
771
    {
772
        $record   = null;
773
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
774
        if (isset($response[$this->evidence])) {
775
            $record = $response[$this->evidence][0];
776
        }
777
778
        return $record;
779
    }
780
781
    /**
782
     * Oddělí z pole podmínek ty jenž patří za ? v URL požadavku
783
     *
784
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
785
     * @param array $conditions pole podmínek   - rendrují se do ()
786
     * @param array $urlParams  pole parametrů  - rendrují za ?
787
     */
788
    public function extractUrlParams(&$conditions, &$urlParams)
789
    {
790
        foreach ($this->urlParams as $urlParam) {
791
            if (isset($conditions[$urlParam])) {
792
                \Ease\Sand::divDataArray($conditions, $urlParams, $urlParam);
793
            }
794
        }
795
    }
796
797
    /**
798
     * Načte data z FlexiBee.
799
     *
800
     * @param string $suffix     dotaz
801
     * @param string|array $conditions Volitelný filtrovací výraz
802
     */
803
    public function getFlexiData($suffix = null, $conditions = null)
804
    {
805
        $urlParams = $this->defaultUrlParams;
806
        if (!is_null($conditions)) {
807
            if (is_array($conditions)) {
808
                $this->extractUrlParams($conditions, $urlParams);
809
                $conditions = $this->flexiUrl($conditions);
810
            }
811
812
            if (strlen($conditions) && ($conditions[0] != '/')) {
813
                $conditions = '/'.rawurlencode('('.($conditions).')');
814
            }
815
        } else {
816
            $conditions = '';
817
        }
818
        if (strlen($suffix)) {
819
            $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.$suffix.'&'.http_build_query($urlParams),
820
                'GET');
821
        } else {
822
            $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.http_build_query($urlParams),
823
                'GET');
824
        }
825
        if (isset($transactions[$this->evidence])) {
826
            $result = $transactions[$this->evidence];
827
        } else {
828
            $result = $transactions;
829
        }
830
831
        return $result;
832
    }
833
834
    /**
835
     * Načte záznam z FlexiBee.
836
     *
837
     * @param int $id ID záznamu
838
     *
839
     * @return int počet načtených položek
840
     */
841 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...
842
    {
843
        $data = [];
844
        if (is_null($id)) {
845
            $id = $this->getMyKey();
846
        }
847
848
        $flexidata = $this->getFlexiData(null, '/'.$id);
849
        if (count($flexidata) == 1) {
850
            $data = current($flexidata);
851
        }
852
        return $this->takeData($data);
853
    }
854
855
    /**
856
     * Převede data do Json formátu pro FlexiBee.
857
     *
858
     * @param array $data
859
     *
860
     * @return string
861
     */
862
    public function jsonizeData($data)
863
    {
864
        $jsonize = [
865
            $this->nameSpace => [
866
                '@version' => $this->protoVersion,
867
                $this->evidence => $this->objectToID($data),
868
            ],
869
        ];
870
871
        if (!is_null($this->action)) {
872
            $jsonize[$this->nameSpace][$this->evidence.'@action'] = $this->action;
873
            $this->action                                         = null;
874
        }
875
876
        return json_encode($jsonize);
877
    }
878
879
    /**
880
     * Test if given record ID exists in FlexiBee.
881
     *
882
     * @param string|int $identifer
883
     */
884
    public function idExists($identifer = null)
885
    {
886
        if (is_null($identifer)) {
887
            $identifer = $this->getMyKey();
888
        }
889
        $flexiData = $this->getFlexiData(
890
            'detail=custom:'.$this->getmyKeyColumn(), $identifer);
891
892
        return $flexiData;
893
    }
894
895
    /**
896
     * Test if given record exists in FlexiBee.
897
     *
898
     * @param array $data
899
     * @return boolean Record presence status
900
     */
901
    public function recordExists($data = null)
902
    {
903
        $found = null;
0 ignored issues
show
Unused Code introduced by
$found 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...
904
        if (is_null($data)) {
905
            $data = $this->getData();
906
        }
907
908
        $res = $this->getColumnsFromFlexibee([$this->myKeyColumn],
909
            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...
910
911
        if (!count($res) || (isset($res['success']) && ($res['success'] == 'false'))
912
            || !count($res[0])) {
913
            $found = false;
914
        } else {
915
            $found = true;
916
        }
917
        return $found;
918
    }
919
920
    /**
921
     * Vrací z FlexiBee sloupečky podle podmínek.
922
     *
923
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
924
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
925
     *                                     sloupečku
926
     * @return array
927
     */
928 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...
929
    {
930
        if (is_int($conditions)) {
931
            $conditions = [$this->getmyKeyColumn() => $conditions];
932
        }
933
934
        $flexiData = $this->getFlexiData('', $conditions);
935
936
        if (!is_null($indexBy)) {
937
            $flexiData = $this->reindexArrayBy($flexiData);
938
        }
939
940
        return $flexiData;
941
    }
942
943
    /**
944
     * Vrací z FlexiBee sloupečky podle podmínek.
945
     *
946
     * @param string[] $columnsList seznam položek
947
     * @param array    $conditions  pole podmínek nebo ID záznamu
948
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
949
     *
950
     * @return array
951
     */
952
    public function getColumnsFromFlexibee($columnsList, $conditions = null,
953
                                           $indexBy = null)
954
    {
955
        $detail = 'full';
956
957
        if (is_int($conditions)) {
958
            $conditions = [$this->getmyKeyColumn() => $conditions];
959
        }
960
961
        if ($columnsList != '*') {
962
            if (is_array($columnsList)) {
963
                $columns = implode(',', array_unique($columnsList));
964
            } else {
965
                $columns = $columnsList;
966
            }
967
            $detail = 'custom:'.$columns;
968
        }
969
970
        $flexiData = $this->getFlexiData('detail='.$detail, $conditions);
971
972
        if (!is_null($indexBy)) {
973
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
974
        }
975
976
        return $flexiData;
977
    }
978
979
    /**
980
     * Vrací kód záznamu.
981
     *
982
     * @param mixed $data
983
     *
984
     * @return string
985
     */
986
    public function getKod($data = null, $unique = true)
987
    {
988
        $kod = null;
989
990
        if (is_null($data)) {
991
            $data = $this->getData();
992
        }
993
994
        if (is_string($data)) {
995
            $data = [$this->nameColumn => $data];
996
        }
997
998
        if (isset($data['kod'])) {
999
            $kod = $data['kod'];
1000
        } else {
1001
            if (isset($data[$this->nameColumn])) {
1002
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
1003
                    \Ease\Sand::rip($data[$this->nameColumn]));
1004
            } else {
1005
                if (isset($data[$this->myKeyColumn])) {
1006
                    $kod = \Ease\Sand::rip($data[$this->myKeyColumn]);
1007
                }
1008
            }
1009
        }
1010
1011
        if (!strlen($kod)) {
1012
            $kod = 'NOTSET';
1013
        }
1014
1015
        if (strlen($kod) > 18) {
1016
            $kodfinal = strtoupper(substr($kod, 0, 18));
1017
        } else {
1018
            $kodfinal = strtoupper($kod);
1019
        }
1020
1021
        if ($unique) {
1022
            $counter = 0;
1023
            if (count($this->codes)) {
1024
                foreach ($this->codes as $codesearch => $keystring) {
1025
                    if (strstr($codesearch, $kodfinal)) {
1026
                        ++$counter;
1027
                    }
1028
                }
1029
            }
1030
            if ($counter) {
1031
                $kodfinal = $kodfinal.$counter;
1032
            }
1033
1034
            $this->codes[$kodfinal] = $kod;
1035
        }
1036
1037
        return $kodfinal;
1038
    }
1039
1040
    /**
1041
     * Write Operation Result.
1042
     *
1043
     * @param array  $resultData
1044
     * @param string $url        URL
1045
     * @return boolean Log save success
1046
     */
1047
    public function logResult($resultData = null, $url = null)
1048
    {
1049
        $logResult = false;
1050
        if (isset($resultData['success']) && ($resultData['success'] == 'false')) {
1051
            if (isset($resultData['message'])) {
1052
                $this->addStatusMessage($resultData['message'], 'warning');
1053
            }
1054
            $this->addStatusMessage('Error '.$this->lastResponseCode.': '.urldecode($url),
1055
                'warning');
1056
            unset($url);
1057
        }
1058
        if (is_null($resultData)) {
1059
            $resultData = $this->lastResult;
1060
        }
1061
        if (isset($url)) {
1062
            $this->logger->addStatusMessage(urldecode($url));
1063
        }
1064
1065
        if (isset($resultData['results'])) {
1066
            $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...
1067
            if ($resultData['success'] == 'false') {
1068
                $status = 'error';
1069
            } else {
1070
                $status = 'success';
1071
            }
1072
            foreach ($resultData['results'] as $result) {
1073
                if (isset($result['request-id'])) {
1074
                    $rid = $result['request-id'];
1075
                } else {
1076
                    $rid = '';
1077
                }
1078
                if (isset($result['errors'])) {
1079
                    foreach ($result['errors'] as $error) {
1080
                        $message = $error['message'];
1081
                        if (isset($error['for'])) {
1082
                            $message .= ' for: '.$error['for'];
1083
                        }
1084
                        if (isset($error['value'])) {
1085
                            $message .= ' value:'.$error['value'];
1086
                        }
1087
                        if (isset($error['code'])) {
1088
                            $message .= ' code:'.$error['code'];
1089
                        }
1090
                        $this->addStatusMessage($rid.': '.$message, $status);
1091
                    }
1092
                }
1093
            }
1094
        }
1095
1096
        if (is_object($this->logger)) {
1097
            $logResult = $this->logger->flush(get_class($this));
1098
        }
1099
        return $logResult;
1100
    }
1101
1102
    /**
1103
     * Save RAW Curl Request & Response to files in Temp directory
1104
     */
1105
    public function saveDebugFiles()
1106
    {
1107
        $tmpdir = sys_get_temp_dir();
1108
        file_put_contents($tmpdir.'/request-'.$this->evidence.'-'.microtime().'.'.$this->format,
1109
            $this->postFields);
1110
        file_put_contents($tmpdir.'/response-'.$this->evidence.'-'.microtime().'.'.$this->format,
1111
            $this->lastCurlResponse);
1112
    }
1113
1114
    /**
1115
     * Připraví data pro odeslání do FlexiBee
1116
     * 
1117
     * @param string $data
1118
     */
1119
    public function setPostFields($data)
1120
    {
1121
        $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...
1122
    }
1123
1124
    /**
1125
     * Generuje fragment url pro filtrování.
1126
     *
1127
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
1128
     *
1129
     * @param array  $data
1130
     * @param string $joiner default and/or
1131
     * @param string $defop  default operator
1132
     *
1133
     * @return string
1134
     */
1135
    public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq')
1136
    {
1137
        $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...
1138
        $parts    = [];
1139
1140
        foreach ($data as $column => $value) {
1141
            if (is_integer($data[$column]) || is_float($data[$column])) {
1142
                $parts[$column] = $column.' eq \''.$data[$column].'\'';
1143
            } elseif (is_bool($data[$column])) {
1144
                $parts[$column] = $data[$column] ? $column.' eq true' : $column.' eq false';
1145
            } elseif (is_null($data[$column])) {
1146
                $parts[$column] = $column." is null";
1147
            } elseif ($value == '!null') {
1148
                $parts[$column] = $column." is not null";
1149
            } else {
1150
                $parts[$column] = $column." $defop '".$data[$column]."'";
1151
            }
1152
        }
1153
1154
        $flexiUrl = implode(' '.$joiner.' ', $parts);
1155
1156
        return $flexiUrl;
1157
    }
1158
1159
    /**
1160
     * Vrací identifikátor objektu code: nebo id:
1161
     *
1162
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1163
     * @return string indentifikátor záznamu reprezentovaného objektem
1164
     */
1165
    public function __toString()
1166
    {
1167
        $myCode = $this->getDataValue('kod');
1168
        if ($myCode) {
1169
            $id = 'code:'.$myCode;
1170
        } else {
1171
            $id = $this->getDataValue('id');
1172
            if (is_null($id)) {
1173
                $this->addToLog('Object Data does not contain code: or id: cannot match with statement!',
1174
                    'warning');
1175
            }
1176
        }
1177
        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...
1178
    }
1179
1180
    /**
1181
     * Gives you FlexiPeeHP class name for Given Evidence
1182
     *
1183
     * @param string $evidence
1184
     * @return string Class name
1185
     */
1186
    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...
1187
    {
1188
        return str_replace(' ', '', ucwords(str_replace('-', ' ', $evidence)));
1189
    }
1190
1191
    /**
1192
     * Vrací hodnotu daného externího ID
1193
     *
1194
     * @param string $want Which ? If empty,you obtain the first one.
1195
     * @return string
1196
     */
1197
    public function getExternalID($want = null)
1198
    {
1199
        $extid = null;
1200
        $ids   = $this->getDataValue('external-ids');
1201
        if (is_null($want)) {
1202
            if (count($ids)) {
1203
                $extid = current($ids);
1204
            }
1205
        } else {
1206
            if (!is_null($ids)) {
1207
                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...
1208
                    if (strstr($id, 'ext:'.$want)) {
1209
                        $extid = str_replace('ext:'.$want.':', '', $id);
1210
                    }
1211
                }
1212
            }
1213
        }
1214
        return $extid;
1215
    }
1216
1217
    /**
1218
     * Obtain actual GlobalVersion
1219
     * Vrací aktuální globální verzi změn
1220
     *
1221
     * @link https://www.flexibee.eu/api/dokumentace/ref/changes-api#globalVersion Globální Verze
1222
     * @return type
1223
     */
1224
    public function getGlobalVersion()
1225
    {
1226
        $globalVersion = null;
1227
        if (!count($this->lastResult) || !isset($this->lastResult['@globalVersion'])) {
1228
            $this->getFlexiData(null,
1229
                ['add-global-version' => 'true', 'limit' => 1]);
1230
        }
1231
1232
        if (isset($this->lastResult['@globalVersion'])) {
1233
            $globalVersion = intval($this->lastResult['@globalVersion']);
1234
        }
1235
1236
        return $globalVersion;
1237
    }
1238
1239
    /**
1240
     * Return the same response format for one and multiplete results
1241
     * 
1242
     * @param array $responseRaw
1243
     * @return array
1244
     */
1245
    public function unifyResponseFormat($responseRaw)
1246
    {
1247
        $response = null;
1248
        $evidence = $this->getResponseEvidence();
1249
        if (is_array($responseRaw)) {
1250
            // Get response body root automatically
1251
            if (array_key_exists($this->nameSpace, $responseRaw)) { //Unifi response format
1252
                $responseBody = $responseRaw[$this->nameSpace];
1253
                if (array_key_exists($evidence, $responseBody)) {
1254
                    $evidenceContent = $responseBody[$evidence];
1255
                    if (array_key_exists(0, $evidenceContent)) {
1256
                        $response[$evidence] = $evidenceContent; //Multiplete Results
1257
                    } else {
1258
                        $response[$evidence][0] = $evidenceContent; //One result
1259
                    }
1260
                } else {
1261
                    $response = $responseBody;
1262
                }
1263
            } else {
1264
                $response = $responseRaw;
1265
            }
1266
        }
1267
        return $response;
1268
    }
1269
1270
    /**
1271
     * Obtain structure for current (or given) evidence
1272
     *
1273
     * @param string $evidence
1274
     * @return array Evidence structure
1275
     */
1276 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...
1277
    {
1278
        $columnsInfo = null;
1279
        if (is_null($evidence)) {
1280
            $evidence = $this->getEvidence();
1281
        }
1282
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1283
        if (isset(\FlexiPeeHP\Properties::$$propsName)) {
1284
            $columnsInfo = Properties::$$propsName;
1285
        }
1286
        return $columnsInfo;
1287
    }
1288
1289
    /**
1290
     * Obtain actions for current (or given) evidence
1291
     *
1292
     * @param string $evidence
1293
     * @return array Evidence structure
1294
     */
1295 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...
1296
    {
1297
        $actionsInfo = null;
1298
        if (is_null($evidence)) {
1299
            $evidence = $this->getEvidence();
1300
        }
1301
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1302
        if (isset(\FlexiPeeHP\Actions::$$propsName)) {
1303
            $actionsInfo = Actions::$$propsName;
1304
        }
1305
        return $actionsInfo;
1306
    }
1307
1308
    /**
1309
     * Obtain info for current (or given) evidence
1310
     *
1311
     * @param string $evidence
1312
     * @return array Evidence info
1313
     */
1314 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...
1315
    {
1316
        $evidencesInfo = null;
1317
        if (is_null($evidence)) {
1318
            $evidence = $this->getEvidence();
1319
        }
1320
        if (isset(EvidenceList::$evidences[$evidence])) {
1321
            $evidencesInfo = EvidenceList::$evidences[$evidence];
1322
        }
1323
        return $evidencesInfo;
1324
    }
1325
1326
    /**
1327
     * Obtain name for current (or given) evidence path
1328
     *
1329
     * @param string $evidence Evidence Path
1330
     * @return array Evidence info
1331
     */
1332 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...
1333
    {
1334
        $evidenceName = null;
1335
        if (is_null($evidence)) {
1336
            $evidence = $this->getEvidence();
1337
        }
1338
        if (isset(EvidenceList::$name[$evidence])) {
1339
            $evidenceName = EvidenceList::$name[$evidence];
1340
        }
1341
        return $evidenceName;
1342
    }
1343
1344
    /**
1345
     * Perform given action (if availble) on current evidence/record
1346
     * @url https://demo.flexibee.eu/devdoc/actions
1347
     * 
1348
     * @param string $action one of evidence actions
1349
     * @param string $method ext|int External method call operation in URL.
1350
     *                               Internal add the @action element to request body
1351
     */
1352
    public function performAction($action, $method = 'ext')
1353
    {
1354
        $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...
1355
        if (is_null($this->actionsAvailable)) {
1356
            $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...
1357
        }
1358
1359
        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...
1360
                $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...
1361
            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...
1362
                case 'ONLY_WITH_INSTANCE_AND_NOT_IN_EDIT':
1363
                case 'ONLY_WITH_INSTANCE': //Add instance
1364
                    $urlSuffix = '/'.$this->__toString().'/'.$action.'.'.$this->format;
1365
                    break;
1366
1367
                default:
1368
                    $urlSuffix = '/'.$action;
1369
                    break;
1370
            }
1371
1372
            switch ($method) {
1373
                case 'int':
1374
                    $this->setAction($action);
1375
                    $result = $this->performRequest(null, 'POST');
1376
                    break;
1377
1378
                default:
1379
                    $result = $this->performRequest($urlSuffix, 'GET');
1380
                    break;
1381
            }
1382
        } else {
1383
            throw new Exception(sprintf(_('Unsupported action %s for evidence %s'),
1384
                $action, $this->getEvidence()));
1385
        }
1386
1387
        return $result;
1388
    }
1389
1390
}
1391