Completed
Push — master ( a03cda...e4da97 )
by Vítězslav
08:44
created

FlexiBeeRO::getCompany()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * FlexiPeeHP - Read Only Access to FlexiBee class.
4
 *
5
 * @author     Vítězslav Dvořák <[email protected]>
6
 * @copyright  (C) 2015,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.2.5';
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, 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
        return $response;
660
    }
661
662
    /**
663
     * Vykonej HTTP požadavek
664
     *
665
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
666
     * @param string $url    URL požadavku
667
     * @param strinf $method HTTP Method GET|POST|PUT|OPTIONS|DELETE
668
     * @param string $format požadovaný formát komunikace
669
     * @return int HTTP Response CODE
670
     */
671
    public function doCurlRequest($url, $method, $format = null)
672
    {
673
        if (is_null($format)) {
674
            $format = $this->format;
675
        }
676
        curl_setopt($this->curl, CURLOPT_URL, $url);
677
// Nastavení samotné operace
678
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
679
//Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411
680
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
681
682
        $httpHeaders = $this->defaultHttpHeaders;
683
        switch ($format) {
684
            case 'json':
685
                $httpHeaders['Accept']       = 'application/json';
686
                $httpHeaders['Content-Type'] = 'application/json';
687
688
                break;
689
            case 'xml':
690
                $httpHeaders['Accept']       = 'application/xml';
691
                $httpHeaders['Content-Type'] = 'application/xml';
692
                break;
693
        }
694
695
        $httpHeadersFinal = [];
696
        foreach ($httpHeaders as $key => $value) {
697
            if (($key == 'User-Agent') && ($value == 'FlexiPeeHP')) {
698
                $value.= ' v'.self::$libVersion;
699
            }
700
            $httpHeadersFinal[] = $key.': '.$value;
701
        }
702
703
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
704
705
// Proveď samotnou operaci
706
        $this->lastCurlResponse = curl_exec($this->curl);
707
708
        $this->info = curl_getinfo($this->curl);
709
710
        $this->lastResponseCode = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
711
        return $this->lastResponseCode;
712
    }
713
714
    /**
715
     * Nastaví druh prováděné akce.
716
     *
717
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
718
     * @param string $action
719
     * @return boolean
720
     */
721
    public function setAction($action)
722
    {
723
        $result = false;
724
        if (is_null($this->actionsAvailable)) {
725
            $this->action = $action;
726
            $result       = true;
727
        } else {
728
            if (array_search($action, $this->actionsAvailable)) {
729
                $this->action = $action;
730
                $result       = true;
731
            }
732
        }
733
        return $result;
734
    }
735
736
    /**
737
     * Convert XML to array.
738
     *
739
     * @param string $xml
740
     *
741
     * @return array
742
     */
743
    public static function xml2array($xml)
744
    {
745
        $arr = [];
746
747
        if (is_string($xml)) {
748
            $xml = simplexml_load_string($xml);
749
        }
750
751
        foreach ($xml->children() as $r) {
752
            if (count($r->children()) == 0) {
753
                $arr[$r->getName()] = strval($r);
754
            } else {
755
                $arr[$r->getName()][] = self::xml2array($r);
756
            }
757
        }
758
759
        return $arr;
760
    }
761
762
    /**
763
     * Odpojení od FlexiBee.
764
     */
765
    public function disconnect()
766
    {
767
        if (is_resource($this->curl)) {
768
            curl_close($this->curl);
769
        }
770
        $this->curl = null;
771
    }
772
773
    public function __destruct()
774
    {
775
        $this->disconnect();
776
    }
777
778
    /**
779
     * Načte řádek dat z FlexiBee.
780
     *
781
     * @param int $recordID id požadovaného záznamu
782
     *
783
     * @return array
784
     */
785
    public function getFlexiRow($recordID)
786
    {
787
        $record   = null;
788
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
789
        if (isset($response[$this->evidence])) {
790
            $record = $response[$this->evidence][0];
791
        }
792
793
        return $record;
794
    }
795
796
    /**
797
     * Oddělí z pole podmínek ty jenž patří za ? v URL požadavku
798
     *
799
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
800
     * @param array $conditions pole podmínek   - rendrují se do ()
801
     * @param array $urlParams  pole parametrů  - rendrují za ?
802
     */
803
    public function extractUrlParams(&$conditions, &$urlParams)
804
    {
805
        foreach ($this->urlParams as $urlParam) {
806
            if (isset($conditions[$urlParam])) {
807
                \Ease\Sand::divDataArray($conditions, $urlParams, $urlParam);
808
            }
809
        }
810
    }
811
812
    /**
813
     * Načte data z FlexiBee.
814
     *
815
     * @param string $suffix     dotaz
816
     * @param string|array $conditions Volitelný filtrovací výraz
817
     */
818
    public function getFlexiData($suffix = null, $conditions = null)
819
    {
820
        $urlParams = $this->defaultUrlParams;
821
        if (!is_null($conditions)) {
822
            if (is_array($conditions)) {
823
                $this->extractUrlParams($conditions, $urlParams);
824
                $conditions = $this->flexiUrl($conditions);
825
            }
826
827
            if (strlen($conditions) && ($conditions[0] != '/')) {
828
                $conditions = '/'.rawurlencode('('.($conditions).')');
829
            }
830
        } else {
831
            $conditions = '';
832
        }
833
        if (strlen($suffix)) {
834
            $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.$suffix.'&'.http_build_query($urlParams),
835
                'GET');
836
        } else {
837
            $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.http_build_query($urlParams),
838
                'GET');
839
        }
840
        if (isset($transactions[$this->evidence])) {
841
            $result = $transactions[$this->evidence];
842
        } else {
843
            $result = $transactions;
844
        }
845
846
        return $result;
847
    }
848
849
    /**
850
     * Načte záznam z FlexiBee.
851
     *
852
     * @param int $id ID záznamu
853
     *
854
     * @return int počet načtených položek
855
     */
856 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...
857
    {
858
        $data = [];
859
        if (is_null($id)) {
860
            $id = $this->getMyKey();
861
        }
862
863
        $flexidata = $this->getFlexiData(null, '/'.$id);
864
        if (count($flexidata) == 1) {
865
            $data = current($flexidata);
866
        }
867
        return $this->takeData($data);
868
    }
869
870
    /**
871
     * Převede data do Json formátu pro FlexiBee.
872
     *
873
     * @param array $data
874
     *
875
     * @return string
876
     */
877
    public function jsonizeData($data)
878
    {
879
        $jsonize = [
880
            $this->nameSpace => [
881
                '@version' => $this->protoVersion,
882
                $this->evidence => $this->objectToID($data),
883
            ],
884
        ];
885
886
        if (!is_null($this->action)) {
887
            $jsonize[$this->nameSpace][$this->evidence.'@action'] = $this->action;
888
            $this->action                                         = null;
889
        }
890
891
        return json_encode($jsonize);
892
    }
893
894
    /**
895
     * Test if given record ID exists in FlexiBee.
896
     *
897
     * @param string|int $identifer
898
     */
899
    public function idExists($identifer = null)
900
    {
901
        if (is_null($identifer)) {
902
            $identifer = $this->getMyKey();
903
        }
904
        $flexiData = $this->getFlexiData(
905
            'detail=custom:'.$this->getmyKeyColumn(), $identifer);
906
907
        return $flexiData;
908
    }
909
910
    /**
911
     * Test if given record exists in FlexiBee.
912
     *
913
     * @param array $data
914
     * @return boolean Record presence status
915
     */
916
    public function recordExists($data = null)
917
    {
918
        $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...
919
        if (is_null($data)) {
920
            $data = $this->getData();
921
        }
922
923
        $res = $this->getColumnsFromFlexibee([$this->myKeyColumn],
924
            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...
925
926
        if (!count($res) || (isset($res['success']) && ($res['success'] == 'false'))
927
            || !count($res[0])) {
928
            $found = false;
929
        } else {
930
            $found = true;
931
        }
932
        return $found;
933
    }
934
935
    /**
936
     * Vrací z FlexiBee sloupečky podle podmínek.
937
     *
938
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
939
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
940
     *                                     sloupečku
941
     * @return array
942
     */
943 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...
944
    {
945
        if (is_int($conditions)) {
946
            $conditions = [$this->getmyKeyColumn() => $conditions];
947
        }
948
949
        $flexiData = $this->getFlexiData('', $conditions);
950
951
        if (!is_null($indexBy)) {
952
            $flexiData = $this->reindexArrayBy($flexiData);
953
        }
954
955
        return $flexiData;
956
    }
957
958
    /**
959
     * Vrací z FlexiBee sloupečky podle podmínek.
960
     *
961
     * @param string[] $columnsList seznam položek
962
     * @param array    $conditions  pole podmínek nebo ID záznamu
963
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
964
     *
965
     * @return array
966
     */
967
    public function getColumnsFromFlexibee($columnsList, $conditions = null,
968
                                           $indexBy = null)
969
    {
970
        $detail = 'full';
971
972
        if (is_int($conditions)) {
973
            $conditions = [$this->getmyKeyColumn() => $conditions];
974
        }
975
976
        if ($columnsList != '*') {
977
            if (is_array($columnsList)) {
978
                $columns = implode(',', array_unique($columnsList));
979
            } else {
980
                $columns = $columnsList;
981
            }
982
            $detail = 'custom:'.$columns;
983
        }
984
985
        $flexiData = $this->getFlexiData('detail='.$detail, $conditions);
986
987
        if (!is_null($indexBy)) {
988
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
989
        }
990
991
        return $flexiData;
992
    }
993
994
    /**
995
     * Vrací kód záznamu.
996
     *
997
     * @param mixed $data
998
     *
999
     * @return string
1000
     */
1001
    public function getKod($data = null, $unique = true)
1002
    {
1003
        $kod = null;
1004
1005
        if (is_null($data)) {
1006
            $data = $this->getData();
1007
        }
1008
1009
        if (is_string($data)) {
1010
            $data = [$this->nameColumn => $data];
1011
        }
1012
1013
        if (isset($data['kod'])) {
1014
            $kod = $data['kod'];
1015
        } else {
1016
            if (isset($data[$this->nameColumn])) {
1017
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
1018
                    \Ease\Sand::rip($data[$this->nameColumn]));
1019
            } else {
1020
                if (isset($data[$this->myKeyColumn])) {
1021
                    $kod = \Ease\Sand::rip($data[$this->myKeyColumn]);
1022
                }
1023
            }
1024
        }
1025
1026
        if (!strlen($kod)) {
1027
            $kod = 'NOTSET';
1028
        }
1029
1030
        if (strlen($kod) > 18) {
1031
            $kodfinal = strtoupper(substr($kod, 0, 18));
1032
        } else {
1033
            $kodfinal = strtoupper($kod);
1034
        }
1035
1036
        if ($unique) {
1037
            $counter = 0;
1038
            if (count($this->codes)) {
1039
                foreach ($this->codes as $codesearch => $keystring) {
1040
                    if (strstr($codesearch, $kodfinal)) {
1041
                        ++$counter;
1042
                    }
1043
                }
1044
            }
1045
            if ($counter) {
1046
                $kodfinal = $kodfinal.$counter;
1047
            }
1048
1049
            $this->codes[$kodfinal] = $kod;
1050
        }
1051
1052
        return $kodfinal;
1053
    }
1054
1055
    /**
1056
     * Write Operation Result.
1057
     *
1058
     * @param array  $resultData
1059
     * @param string $url        URL
1060
     * @return boolean Log save success
1061
     */
1062
    public function logResult($resultData = null, $url = null)
1063
    {
1064
        $logResult = false;
1065
        if (isset($resultData['success']) && ($resultData['success'] == 'false')) {
1066
            if (isset($resultData['message'])) {
1067
                $this->addStatusMessage($resultData['message'], 'warning');
1068
            }
1069
            $this->addStatusMessage('Error '.$this->lastResponseCode.': '.urldecode($url),
1070
                'warning');
1071
            unset($url);
1072
        }
1073
        if (is_null($resultData)) {
1074
            $resultData = $this->lastResult;
1075
        }
1076
        if (isset($url)) {
1077
            $this->logger->addStatusMessage(urldecode($url));
1078
        }
1079
1080
        if (isset($resultData['results'])) {
1081
            $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...
1082
            if ($resultData['success'] == 'false') {
1083
                $status = 'error';
1084
            } else {
1085
                $status = 'success';
1086
            }
1087
            foreach ($resultData['results'] as $result) {
1088
                if (isset($result['request-id'])) {
1089
                    $rid = $result['request-id'];
1090
                } else {
1091
                    $rid = '';
1092
                }
1093
                if (isset($result['errors'])) {
1094
                    foreach ($result['errors'] as $error) {
1095
                        $message = $error['message'];
1096
                        if (isset($error['for'])) {
1097
                            $message .= ' for: '.$error['for'];
1098
                        }
1099
                        if (isset($error['value'])) {
1100
                            $message .= ' value:'.$error['value'];
1101
                        }
1102
                        if (isset($error['code'])) {
1103
                            $message .= ' code:'.$error['code'];
1104
                        }
1105
                        $this->addStatusMessage($rid.': '.$message, $status);
1106
                    }
1107
                }
1108
            }
1109
        }
1110
1111
        if (is_object($this->logger)) {
1112
            $logResult = $this->logger->flush(get_class($this));
1113
        }
1114
        return $logResult;
1115
    }
1116
1117
    /**
1118
     * Save RAW Curl Request & Response to files in Temp directory
1119
     */
1120
    public function saveDebugFiles()
1121
    {
1122
        $tmpdir = sys_get_temp_dir();
1123
        file_put_contents($tmpdir.'/request-'.$this->evidence.'-'.microtime().'.'.$this->format,
1124
            $this->postFields);
1125
        file_put_contents($tmpdir.'/response-'.$this->evidence.'-'.microtime().'.'.$this->format,
1126
            $this->lastCurlResponse);
1127
    }
1128
1129
    /**
1130
     * Připraví data pro odeslání do FlexiBee
1131
     * 
1132
     * @param string $data
1133
     */
1134
    public function setPostFields($data)
1135
    {
1136
        $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...
1137
    }
1138
1139
    /**
1140
     * Generuje fragment url pro filtrování.
1141
     *
1142
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
1143
     *
1144
     * @param array  $data
1145
     * @param string $joiner default and/or
1146
     * @param string $defop  default operator
1147
     *
1148
     * @return string
1149
     */
1150
    public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq')
1151
    {
1152
        $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...
1153
        $parts    = [];
1154
1155
        foreach ($data as $column => $value) {
1156
            if (is_integer($data[$column]) || is_float($data[$column])) {
1157
                $parts[$column] = $column.' eq \''.$data[$column].'\'';
1158
            } elseif (is_bool($data[$column])) {
1159
                $parts[$column] = $data[$column] ? $column.' eq true' : $column.' eq false';
1160
            } elseif (is_null($data[$column])) {
1161
                $parts[$column] = $column." is null";
1162
            } else {
1163
                switch ($value) {
1164
                    case '!null':
1165
                        $parts[$column] = $column." is not null";
1166
                        break;
1167
                    case 'is empty':
1168
                    case 'is not empty':
1169
                        $parts[$column] = $column.' '.$value;
1170
                        break;
1171
                    default:
1172
                        $parts[$column] = $column." $defop '".$data[$column]."'";
1173
                        break;
1174
                }
1175
        }
1176
        }
1177
1178
        $flexiUrl = implode(' '.$joiner.' ', $parts);
1179
1180
        return $flexiUrl;
1181
    }
1182
1183
    /**
1184
     * Vrací identifikátor objektu code: nebo id:
1185
     *
1186
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1187
     * @return string indentifikátor záznamu reprezentovaného objektem
1188
     */
1189
    public function __toString()
1190
    {
1191
        $myCode = $this->getDataValue('kod');
1192
        if ($myCode) {
1193
            $id = 'code:'.$myCode;
1194
        } else {
1195
            $id = $this->getDataValue('id');
1196
            if (is_null($id)) {
1197
                $this->addToLog('Object Data does not contain code: or id: cannot match with statement!',
1198
                    'warning');
1199
            }
1200
        }
1201
        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...
1202
    }
1203
1204
    /**
1205
     * Gives you FlexiPeeHP class name for Given Evidence
1206
     *
1207
     * @param string $evidence
1208
     * @return string Class name
1209
     */
1210
    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...
1211
    {
1212
        return str_replace(' ', '', ucwords(str_replace('-', ' ', $evidence)));
1213
    }
1214
1215
    /**
1216
     * Vrací hodnotu daného externího ID
1217
     *
1218
     * @param string $want Which ? If empty,you obtain the first one.
1219
     * @return string
1220
     */
1221
    public function getExternalID($want = null)
1222
    {
1223
        $extid = null;
1224
        $ids   = $this->getDataValue('external-ids');
1225
        if (is_null($want)) {
1226
            if (count($ids)) {
1227
                $extid = current($ids);
1228
            }
1229
        } else {
1230
            if (!is_null($ids)) {
1231
                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...
1232
                    if (strstr($id, 'ext:'.$want)) {
1233
                        $extid = str_replace('ext:'.$want.':', '', $id);
1234
                    }
1235
                }
1236
            }
1237
        }
1238
        return $extid;
1239
    }
1240
1241
    /**
1242
     * Obtain actual GlobalVersion
1243
     * Vrací aktuální globální verzi změn
1244
     *
1245
     * @link https://www.flexibee.eu/api/dokumentace/ref/changes-api#globalVersion Globální Verze
1246
     * @return type
1247
     */
1248
    public function getGlobalVersion()
1249
    {
1250
        $globalVersion = null;
1251
        if (!count($this->lastResult) || !isset($this->lastResult['@globalVersion'])) {
1252
            $this->getFlexiData(null,
1253
                ['add-global-version' => 'true', 'limit' => 1]);
1254
        }
1255
1256
        if (isset($this->lastResult['@globalVersion'])) {
1257
            $globalVersion = intval($this->lastResult['@globalVersion']);
1258
        }
1259
1260
        return $globalVersion;
1261
    }
1262
1263
    /**
1264
     * Return the same response format for one and multiplete results
1265
     * 
1266
     * @param array $responseRaw
1267
     * @return array
1268
     */
1269
    public function unifyResponseFormat($responseRaw)
1270
    {
1271
        $response = null;
1272
        $evidence = $this->getResponseEvidence();
1273
        if (is_array($responseRaw)) {
1274
            // Get response body root automatically
1275
            if (array_key_exists($this->nameSpace, $responseRaw)) { //Unifi response format
1276
                $responseBody = $responseRaw[$this->nameSpace];
1277
                if (array_key_exists($evidence, $responseBody)) {
1278
                    $evidenceContent = $responseBody[$evidence];
1279
                    if (array_key_exists(0, $evidenceContent)) {
1280
                        $response[$evidence] = $evidenceContent; //Multiplete Results
1281
                    } else {
1282
                        $response[$evidence][0] = $evidenceContent; //One result
1283
                    }
1284
                } else {
1285
                    $response = $responseBody;
1286
                }
1287
            } else {
1288
                $response = $responseRaw;
1289
            }
1290
        }
1291
        return $response;
1292
    }
1293
1294
    /**
1295
     * Obtain structure for current (or given) evidence
1296
     *
1297
     * @param string $evidence
1298
     * @return array Evidence structure
1299
     */
1300 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...
1301
    {
1302
        $columnsInfo = null;
1303
        if (is_null($evidence)) {
1304
            $evidence = $this->getEvidence();
1305
        }
1306
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1307
        if (isset(\FlexiPeeHP\Properties::$$propsName)) {
1308
            $columnsInfo = Properties::$$propsName;
1309
        }
1310
        return $columnsInfo;
1311
    }
1312
1313
    /**
1314
     * Obtain actions for current (or given) evidence
1315
     *
1316
     * @param string $evidence
1317
     * @return array Evidence structure
1318
     */
1319 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...
1320
    {
1321
        $actionsInfo = null;
1322
        if (is_null($evidence)) {
1323
            $evidence = $this->getEvidence();
1324
        }
1325
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1326
        if (isset(\FlexiPeeHP\Actions::$$propsName)) {
1327
            $actionsInfo = Actions::$$propsName;
1328
        }
1329
        return $actionsInfo;
1330
    }
1331
1332
    /**
1333
     * Obtain info for current (or given) evidence
1334
     *
1335
     * @param string $evidence
1336
     * @return array Evidence info
1337
     */
1338 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...
1339
    {
1340
        $evidencesInfo = null;
1341
        if (is_null($evidence)) {
1342
            $evidence = $this->getEvidence();
1343
        }
1344
        if (isset(EvidenceList::$evidences[$evidence])) {
1345
            $evidencesInfo = EvidenceList::$evidences[$evidence];
1346
        }
1347
        return $evidencesInfo;
1348
    }
1349
1350
    /**
1351
     * Obtain name for current (or given) evidence path
1352
     *
1353
     * @param string $evidence Evidence Path
1354
     * @return array Evidence info
1355
     */
1356 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...
1357
    {
1358
        $evidenceName = null;
1359
        if (is_null($evidence)) {
1360
            $evidence = $this->getEvidence();
1361
        }
1362
        if (isset(EvidenceList::$name[$evidence])) {
1363
            $evidenceName = EvidenceList::$name[$evidence];
1364
        }
1365
        return $evidenceName;
1366
    }
1367
1368
    /**
1369
     * Perform given action (if availble) on current evidence/record
1370
     * @url https://demo.flexibee.eu/devdoc/actions
1371
     * 
1372
     * @param string $action one of evidence actions
1373
     * @param string $method ext|int External method call operation in URL.
1374
     *                               Internal add the @action element to request body
1375
     */
1376
    public function performAction($action, $method = 'ext')
1377
    {
1378
        $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...
1379
        if (is_null($this->actionsAvailable)) {
1380
            $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...
1381
        }
1382
1383
        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...
1384
                $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...
1385
            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...
1386
                case 'ONLY_WITH_INSTANCE_AND_NOT_IN_EDIT':
1387
                case 'ONLY_WITH_INSTANCE': //Add instance
1388
                    $urlSuffix = '/'.$this->__toString().'/'.$action.'.'.$this->format;
1389
                    break;
1390
1391
                default:
1392
                    $urlSuffix = '/'.$action;
1393
                    break;
1394
            }
1395
1396
            switch ($method) {
1397
                case 'int':
1398
                    $this->setAction($action);
1399
                    $result = $this->performRequest(null, 'POST');
1400
                    break;
1401
1402
                default:
1403
                    $result = $this->performRequest($urlSuffix, 'GET');
1404
                    break;
1405
            }
1406
        } else {
1407
            throw new \Exception(sprintf(_('Unsupported action %s for evidence %s'),
1408
                $action, $this->getEvidence()));
1409
        }
1410
1411
        return $result;
1412
    }
1413
1414
}
1415