Passed
Push — master ( 20f309...c1f576 )
by Vítězslav
01:56
created

FlexiBeeRW::takeData()   B

Complexity

Conditions 10
Paths 3

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 10

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 14
cts 14
cp 1
rs 7.6666
c 0
b 0
f 0
cc 10
nc 3
nop 1
crap 10

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * FlexiPeeHP - Třída pro zápis do FlexiBee.
4
 *
5
 * @author     Vítězslav Dvořák <[email protected]>
6
 * @copyright  (C) 2015-2017 Spoje.Net
7
 */
8
9
namespace FlexiPeeHP;
10
11
/**
12
 * Základní třída pro zápis do FlexiBee
13
 *
14
 * @url https://demo.flexibee.eu/devdoc/http-operations
15
 */
16
class FlexiBeeRW extends FlexiBeeRO
17
{
18
    /**
19
     * Sloupeček obsahující datum vložení záznamu do shopu.
20
     *
21
     * @var string
22
     */
23
    public $myCreateColumn = 'false';
24
25
    /**
26
     * Slopecek obsahujici datum poslení modifikace záznamu do shopu.
27
     *
28
     * @var string
29
     */
30
    public $myLastModifiedColumn = 'lastUpdate';
31
32
    /**
33
     * Last Inserted ID.
34
     *
35
     * @var int
36
     */
37
    public $lastInsertedID = null;
38
39
    /**
40
     * Array of fields for next curl POST operation
41
     * 
42
     * @var string
43
     */
44
    public $postFields = null;
45
46
    /**
47
     * Transaction processing mode
48
     * 
49
     * @link https://www.flexibee.eu/api/dokumentace/ref/tx/ Transakční zpracování
50
     * @var boolean
51
     */
52
    public $atomic = null;
53
54
    /**
55 17
     * SetUp Object to be ready for work
56
     *
57 17
     * @param array $options Object Options (authSessionId,user,password,
58 17
     *                                       url,company,evidence,
59 17
     *                                       prefix,defaultUrlParams,debug,
60
     *                                       detail,offline,atomic,filter,ignore404
61
     */
62 17
    public function setUp($options = array())
63
    {
64
        if (array_key_exists('atomic', $options)) {
65 17
            $this->atomic = (boolean) $options['atomic'];
66 7
        }
67
        return parent::setUp($options);
0 ignored issues
show
Bug introduced by
Are you sure the usage of parent::setUp($options) targeting FlexiPeeHP\FlexiBeeRO::setUp() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
68
    }
69
70
    /**
71 7
     * Save record (if evidence allow to).
72 10
     * Uloží záznam (pokud to evidence dovoluje)
73 10
     *
74 10
     * @param array $data Data to save
75 17
     * @throws Exception Evidence does not support Import
76
     *
77 17
     * @return array odpověď
78
     */
79
    public function insertToFlexiBee($data = null)
80 17
    {
81 17
        if (is_null($data)) {
82
            $data = $this->getData();
83
        }
84
        $this->postFields = $this->getJsonizedData($data,
85
            $this->debug ? JSON_PRETTY_PRINT : 0);
86
        return $this->performRequest(null, 'PUT');
87
    }
88
89
    /**
90
     * Parse Response array
91
     *
92
     * @param array $responseDecoded
93
     * @param int $responseCode Request Response Code
94
     *
95
     * @return array main data part of response
96
     */
97
    public function parseResponse($responseDecoded, $responseCode)
98
    {
99
        switch ($responseCode) {
100
            case 201: //Success Write
101
                if (isset($responseDecoded[$this->resultField][0]['id'])) {
102
                    $this->lastInsertedID = $responseDecoded[$this->resultField][0]['id'];
103
                    $this->setMyKey($this->lastInsertedID);
104
                } else {
105
                    $this->lastInsertedID = null;
106
                }
107
                if (count($this->chained)) {
108
                    $this->assignResultIDs($this->extractResultIDs($responseDecoded[$this->resultField]));
109
                }
110
        }
111
        return parent::parseResponse($responseDecoded, $responseCode);
112
    }
113
114
    /**
115
     * Assign result IDs to its source objects
116
     * 
117
     * @param array $candidates FlexiBee insert IDs  prepared by extractResultIDs()
118
     */
119
    public function assignResultIDs($candidates)
120
    {
121
        foreach ($this->chained as $chid => $chained) {
122
            $chainedEvidence = $chained->getEvidence();
123
            $chainedExtid    = $chained->getRecordID();
124
            if (is_array($chainedExtid)) { //if there are more IDs
125
                foreach ($chainedExtid as $extId) { //find external ID in format ext:.....
126
                    if (stripos($extId, 'ext:') === 0) {
127
                        $chainedExtid = $extId;
128
                        break;
129
                    }
130
                }
131
            }
132
            $chained->getData();
133
            if (isset($candidates[$chainedEvidence][$chainedExtid])) {
134
                $chained->setMyKey($candidates[$chainedEvidence][$chainedExtid]);
135
                $chained->setDataValue('external-ids', [$chainedExtid]);
136
            }
137
            if (count($this->chained[$chid]->chained)) {
138
                $this->chained[$chid]->assignResultIDs($candidates);
139
            }
140
        }
141
    }
142
143
    /**
144
     * Extract IDs from FlexiBee response Array
145
     * 
146
     * @param array $resultInfo FlexiBee response
147
     * 
148
     * @return array List of [ 'evidence1'=>[ 'original-id'=>numericID,'original-id2'=>numericID2 ], 'evidence2'=> ... ]
149
     */
150
    public function extractResultIDs($resultInfo)
151
    {
152
        $candidates = [];
153
        foreach ($resultInfo as $insertResult) {
154
            $newID = $insertResult['id'];
155
            if (array_key_exists('request-id', $insertResult)) {
156
                $extid = $insertResult['request-id'];
157
            } else {
158
                $extid = null;
159
            }
160
            $evidence                      = explode('/', $insertResult['ref'])[3];
161
            $candidates[$evidence][$extid] = $newID;
162
        }
163
        return $candidates;
164
    }
165
166
    /**
167
     * Give you last inserted record ID.
168
     * 
169
     * @return int
170
     */
171
    public function getLastInsertedId()
172
    {
173
        return $this->lastInsertedID;
174
    }
175
176
    /**
177
     * Smaže záznam
178
     * Delete record in FlexiBee
179
     *
180
     * @param int|string $id identifikátor záznamu
181
     * 
182
     * @return boolean Response code is 200 ?
183
     */
184
    public function deleteFromFlexiBee($id = null)
185
    {
186
        if (is_null($id)) {
187
            $id = $this->getMyKey();
188
        }
189
        $this->performRequest($this->getEvidenceUrl().'/'.$id.'.'.$this->format,
190
            'DELETE');
191
        return $this->lastResponseCode == 200;
192
    }
193
194
    /**
195
     * Control for existing column names in evidence and take data
196
     *
197
     * @param array $data Data to keep
198
     * 
199
     * @return int number of records taken
200
     */
201
    public function takeData($data)
202
    {
203
        if ($this->debug === true) {
204 17
            $fbRelations = [];
205
            $fbColumns   = $this->getColumnsInfo();
206 17
            foreach ($this->getRelationsInfo() as $relation) {
207 17
                if (is_array($relation) && isset($relation['url'])) {
208 17
                    $fbRelations[$relation['url']] = $relation['url'];
209 17
                }
210 17
            }
211 17
            if (count($fbColumns)) {
212 17
                foreach ($data as $key => $value) {
213
                    if (!array_key_exists($key, $fbColumns)) {
214
215
                        if (!array_key_exists($key, $fbRelations)) {
216
                            $this->addStatusMessage(sprintf('unknown column %s for evidence %s',
217
                                    $key, $this->getEvidence()), 'warning');
218
                        } else {
219
                            if (!is_array($value)) {
220
                                $this->addStatusMessage(sprintf('subevidence %s in evidence %s must bee an array',
221
                                        $key, $this->getEvidence()), 'warning');
222 17
                            }
223
                        }
224 17
                    }
225 17
                }
226 17
            }
227 17
        }
228 17
        return parent::takeData($data);
229 17
    }
230 17
231
    /**
232
     * Control data for mandatory columns presence.
233
     *
234
     * @deprecated since version 1.8.7
235
     * 
236
     * @param array $data
237
     * 
238
     * @return array List of missing columns. Empty if all is ok
239
     */
240
    public function controlMandatoryColumns($data = null)
241
    {
242
        if (is_null($data)) {
243
            $data = $this->getData();
244
        }
245
        $missingMandatoryColumns = [];
246
        if (!empty($data) && count($data)) {
247
            $fbColumns = $this->getColumnsInfo();
248
            if (count($fbColumns)) {
249
                foreach ($fbColumns as $columnName => $columnInfo) {
250
                    $mandatory = ($columnInfo['mandatory'] == 'true');
251
                    if ($mandatory && !array_key_exists($columnName, $data)) {
252
                        $missingMandatoryColumns[$columnName] = $columnInfo['name'];
253
                    }
254
                }
255
            }
256
        }
257
        return $missingMandatoryColumns;
258
    }
259
260
    /**
261
     * Control data for readonly columns presence.
262
     *
263
     * @param array $data
264
     * 
265
     * @return array List of ReadOnly columns. Empty if all is ok
266
     */
267
    public function controlReadOnlyColumns($data = null)
268
    {
269
        if (is_null($data)) {
270
            $data = $this->getData();
271
        }
272
273
        $readonlyColumns = [];
274
275
        $fbColumns = $this->getColumnsInfo();
276
        if (!empty($fbColumns) && count($fbColumns)) {
277
            foreach ($fbColumns as $columnName => $columnInfo) {
278
                $writable = ($columnInfo['isWritable'] == 'true');
279
                if (!$writable && !array_key_exists($columnName, $data)) {
280
                    $readonlyColumns[$columnName] = $columnInfo['name'];
281
                }
282
            }
283
        }
284
        return $readonlyColumns;
285
    }
286
287
    /**
288
     * Convert Timestamp to FlexiBee Date format.
289
     *
290
     * @param int $timpestamp
291
     *
292
     * @return string FlexiBee Date or NULL
293
     */
294
    public static function timestampToFlexiDate($timpestamp = null)
295
    {
296
        $flexiDate = null;
297
        if (!is_null($timpestamp)) {
298
            $date      = new \DateTime();
299
            $date->setTimestamp($timpestamp);
300
            $flexiDate = $date->format('Y-m-d');
301
        }
302
        return $flexiDate;
303
    }
304
305
    /**
306
     * Convert Timestamp to Flexi DateTime format.
307
     *
308
     * @param int $timpestamp
309
     *
310
     * @return string FlexiBee DateTime or NULL
311
     */
312
    public static function timestampToFlexiDateTime($timpestamp = null)
313
    {
314
        $flexiDateTime = null;
315
        if (!is_null($timpestamp)) {
316
            $date          = new \DateTime();
317
            $date->setTimestamp($timpestamp);
318
            $flexiDateTime = $date->format('Y-m-dTH:i:s');
319
        }
320
        return $flexiDateTime;
321
    }
322
323
    /**
324
     * Add Data to evidence Branch
325
     * Přidá data do větve
326
     *
327
     * @thanksto Karel Běl
328
     *
329
     * @see Relations
330
     *
331
     * @param array  $data pole dat
332
     * @param string $relationPath path evidence (relation) pro vkládaná data
333
     *
334
     * @return boolean Operation success
335
     */
336
    public function addArrayToBranch($data, $relationPath = 'polozkyDokladu')
337
    {
338
        $currentBranchData = $this->getDataValue($relationPath);
339
        $branchData        = $currentBranchData;
340
        $branchData[]      = $data;
341
        if (is_array($this->getEvidence()) && array_key_exists('bezPolozek',
0 ignored issues
show
introduced by
The condition is_array($this->getEvidence()) is always false.
Loading history...
342
                $this->getColumnsInfo())) {
343 17
            $this->setDataValue('bezPolozek', false);
344
        }
345 17
        return $this->setDataValue($relationPath, $branchData);
346
    }
347 17
348 17
    /**
349 15
     * Vloží do větve data z objektu
350 15
     *
351 15
     * @param FlexiBeeRO $object objekt evidence
352 4
     */
353 4
    public function addObjectToBranch($object)
354
    {
355 15
        $this->addArrayToBranch([$object->getEvidence() => $object->getData()]);
356 15
    }
357 15
358 15
    /**
359
     * Přidá uživatelskou vazbu
360
     *
361 15
     * @see https://www.flexibee.eu/api/dokumentace/ref/uzivatelske-vazby/
362 4
     * @param string $vazba
363 4
     */
364 4
    public function vazbaAdd($vazba)
365 4
    {
366 4
        $this->addArrayToBranch(['uzivatelska-vazba' => $vazba],
367
            'uzivatelske-vazby');
368 15
    }
369 15
370 15
    /**
371 15
     * Smaže uživatelskou vazbu
372 15
     *
373 15
     * @see https://www.flexibee.eu/api/dokumentace/ref/uzivatelske-vazby/
374 17
     * @param string $vazba
375 17
     */
376
    public function vazbaDel($vazba)
377
    {
378 15
        $this->setDataValue('uzivatelska-vazba@action', 'delete');
379
        $this->addArrayToBranch(['uzivatelska-vazba' => $vazba],
380
            'uzivatelske-vazby');
381
    }
382
383
    /**
384
     * Převede data do Json formátu pro FlexiBee.
385
     * Pokud jsou štítky pole, jsou převedeny na seznam oddělený čárkou.
386
     * Convert data to FlexiBee like Json format.
387
     * Array of Labels is converted to coma separated list
388
     *
389
     * @param array $data
390
     * @param int   $options json_encode options like JSON_PRETTY_PRINT etc 
391
     *
392
     * @return string
393
     */
394
    public function getJsonizedData($data = null, $options = 0)
395
    {
396
        if (is_null($data)) {
397
            $data = $this->getData();
398
        }
399
400
        if (array_key_exists('stitky', $data)) {
401
            if (is_array($data['stitky'])) {
402
                $data['stitky'] = implode(',', $data['stitky']);
403
            }
404
        }
405
        $dataToJsonize = parent::getJsonizedData($data, $options);
406
        return $dataToJsonize;
407
    }
408
409
    /**
410
     * Get Data Fragment specific for current object
411
     * 
412
     * @param array $data
413
     * 
414
     * @return array
415
     */
416
    public function getDataForJSON($data = null)
417
    {
418
        if (is_null($data)) {
419
            $data = $this->getData();
420
        }
421
        $dataForJSON = parent::getDataForJSON($data);
422
        if (!is_null($this->atomic)) {
0 ignored issues
show
introduced by
The condition is_null($this->atomic) is always false.
Loading history...
423
            $dataForJSON['@atomic'] = $this->atomic;
424
        }
425
        return $dataForJSON;
426
    }
427
428
    /**
429
     * Insert current data into FlexiBee and load actual record data back
430
     *
431
     * @param array $data Initial data to save
432
     * 
433
     * @return boolean Operation success
434
     */
435
    public function sync($data = null)
436
    {
437
        $this->insertToFlexiBee($data);
438
        $insertResult = $this->lastResponseCode;
439
        if ($insertResult == 201) {
440
            $id = $this->getRecordID();
441
            $this->dataReset();
442
            $this->loadFromFlexiBee($id);
443
        }
444
        $loadResult = $this->lastResponseCode;
445
        return ($insertResult + $loadResult) == 401;
446
    }
447
448
    /**
449
     * Perform given action (if availble) on current evidence/record
450
     * @url https://demo.flexibee.eu/devdoc/actions
451
     *
452
     * @param string $action one of evidence actions
453
     * @param string $method ext|int External method call operation in URL.
454
     *                               Internal add the @action element to request body
455
     *
456
     * @return boolean operation success
457
     */
458
    public function performAction($action, $method = 'int')
459
    {
460
        $actionsAvailble = $this->getActionsInfo();
461
462
        if (is_array($actionsAvailble) && array_key_exists($action,
463
                $actionsAvailble)) {
464
            switch ($actionsAvailble[$action]['actionMakesSense']) {
465
                case 'ONLY_WITH_INSTANCE_AND_NOT_IN_EDIT':
466
                case 'ONLY_WITH_INSTANCE': //Add instance
467
                    $urlSuffix = '/'.$this->__toString().'/'.$action;
468
                    break;
469
470
                default:
471
                    $urlSuffix = '/'.$action;
472
                    break;
473
            }
474
475
            switch ($method) {
476
                case 'int':
477
                    $this->setAction($action);
478
                    $this->setPostFields($this->getJsonizedData(['id' => $this]));
479
                    $this->performRequest(null, 'POST');
480
                    $result = $this->lastResponseCode == 201;
481
                    break;
482
483
                default:
484
                    $result = $this->performRequest($this->evidenceUrlWithSuffix($urlSuffix),
485
                        'GET');
486
                    break;
487
            }
488
        } else {
489
            throw new \Exception(sprintf(_('Unsupported action %s for evidence %s'),
490
                    $action, $this->getEvidence()));
491
        }
492
493
        return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result also could return the type array which is incompatible with the documented return type boolean.
Loading history...
494
    }
495
496
    /**
497
     * Add External ID to Current Record
498
     * 
499
     * @param string $extId ext:whatever:123 or simplay whatever:123
500
     * 
501
     * @return array Insert result
502
     */
503
    public function addExternalID($extId)
504
    {
505
        return $this->insertToFlexiBee(['id' => [$this->getRecordID(), 'ext:'.preg_replace('/^ext:/', '', $extId)]]);
506
    }
507
508
    /**
509
     * Change Value of external id identified by selector. Add new if not exists
510
     * 
511
     * @param string     $selector ext:$selector:$newValue
512
     * @param string|int $newValue string or number
513
     * @param string|int $forID    Other than current record id
514
     * 
515
     * @return array operation result
516
     */
517
    public function changeExternalID($selector, $newValue, $forID = null)
518
    {
519
        $change['@removeExternalIds'] = 'ext:'.$selector.':';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$change was never initialized. Although not strictly required by PHP, it is generally a good practice to add $change = array(); before regardless.
Loading history...
520
        $change['id']                 = [is_null($forID) ? $this->getRecordID() : $forID,
521
            'ext:'.$selector.':'.$newValue];
522
        return $this->insertToFlexiBee($change);
523
    }
524
}
525