Test Failed
Push — master ( 0a6b17...c396e6 )
by Vítězslav
07:31
created

FlexiBeeRW::takeData()   D

Complexity

Conditions 10
Paths 3

Size

Total Lines 29
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 18
nc 3
nop 1
dl 0
loc 29
rs 4.8196
c 1
b 0
f 0
ccs 0
cts 25
cp 0
crap 110

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
     * Save record (if evidence allow to).
48
     * Uloží záznam (pokud to evidence dovoluje)
49
     *
50
     * @param array $data Data to save
51
     * @throws Exception Evidence does not support Import
52
     *
53
     * @return array odpověď
54
     */
55 17
    public function insertToFlexiBee($data = null)
56
    {
57 17
        $info = $this->getEvidenceInfo();
58 17
        switch ($info['importStatus']) {
59 17
            case 'DISALLOWED':
60
                throw new \Exception(sprintf('Inserting data to r/o evidence %s',
61
                        $this->getEvidence()));
62 17
            case 'NOT_DIRECT':
63
                throw new \Exception(sprintf('Inserting data to slave only evidence %s',
64
                        $this->getEvidence()));
65 17
            case 'NOT_DOCUMENTED':
66 7
                if ($this->debug === true) {
67
                    $this->addStatusMessage(sprintf('Inserting data to undocumneted evidence %s',
68
                            $this->getEvidence()));
69
                }
70
71 7
                break;
72 10
            case 'SUPPORTED':
73 10
            default:
74 10
                break;
75 17
        }
76
77 17
        if (is_null($data)) {
78
            $data = $this->getData();
79
        }
80 17
        $this->postFields = $this->jsonizeData($data);
81 17
        return $this->performRequest(null, 'PUT');
82
    }
83
84
    /**
85
     * Give you last inserted record ID.
86
     * 
87
     * @return int
88
     */
89
    public function getLastInsertedId()
90
    {
91
        return $this->lastInsertedID;
92
    }
93
94
    /**
95
     * Smaže záznam
96
     * Delete record in FlexiBee
97
     *
98
     * @param int|string $id identifikátor záznamu
99
     * @return boolean Response code is 200 ?
100
     */
101
    public function deleteFromFlexiBee($id = null)
102
    {
103
        if (is_null($id)) {
104
            $id = $this->getMyKey();
105
        }
106
        $this->performRequest($this->getEvidenceUrl().'/'.$id.'.'.$this->format,
107
            'DELETE');
108
        return $this->lastResponseCode == 200;
109
    }
110
111
    /**
112
     * Control for existing column names in evidence and take data
113
     *
114
     * @param array $data Data to keep
115
     * @return int number of records taken
116
     */
117
    public function takeData($data)
118
    {
119
        if ($this->debug === true) {
120
            $fbRelations = [];
121
            $fbColumns   = $this->getColumnsInfo();
122
            foreach ($this->getRelationsInfo() as $relation) {
123
                if (is_array($relation) && isset($relation['url'])) {
124
                    $fbRelations[$relation['url']] = $relation['url'];
125
                }
126
            }
127
            if (count($fbColumns)) {
128
                foreach ($data as $key => $value) {
129
                    if (!array_key_exists($key, $fbColumns)) {
130
131
                        if (!array_key_exists($key, $fbRelations)) {
132
                            $this->addStatusMessage(sprintf('unknown column %s for evidence %s',
133
                                    $key, $this->getEvidence()), 'warning');
134
                        } else {
135
                            if (!is_array($value)) {
136
                                $this->addStatusMessage(sprintf('subevidence %s in evidence %s must bee an array',
137
                                        $key, $this->getEvidence()), 'warning');
138
                            }
139
                        }
140
                    }
141
                }
142
            }
143
        }
144
        return parent::takeData($data);
145
    }
146
147
    /**
148
     * Control data for mandatory columns presence.
149
     *
150
     * @param array $data
151
     * @return array List of missing columns. Empty if all is ok
152
     */
153 View Code Duplication
    public function controlMandatoryColumns($data = 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...
154
    {
155
        if (is_null($data)) {
156
            $data = $this->getData();
157
        }
158
159
        $missingMandatoryColumns = [];
160
161
        $fbColumns = $this->getColumnsInfo();
162
        foreach ($fbColumns as $columnName => $columnInfo) {
163
            $mandatory = ($columnInfo['mandatory'] == 'true');
164
            if ($mandatory && !array_key_exists($columnName, $data)) {
165
                $missingMandatoryColumns[$columnName] = $columnInfo['name'];
166
            }
167
        }
168
169
        return $missingMandatoryColumns;
170
    }
171
172
    /**
173
     * Control data for readonly columns presence.
174
     *
175
     * @param array $data
176
     * @return array List of ReadOnly columns. Empty if all is ok
177
     */
178 View Code Duplication
    public function controlReadOnlyColumns($data = 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...
179
    {
180
        if (is_null($data)) {
181
            $data = $this->getData();
182
        }
183
184
        $readonlyColumns = [];
185
186
        $fbColumns = $this->getColumnsInfo();
187
        foreach ($fbColumns as $columnName => $columnInfo) {
188
            $writable = ($columnInfo['isWritable'] == 'true');
189
            if (!$writable && !array_key_exists($columnName, $data)) {
190
                $readonlyColumns[$columnName] = $columnInfo['name'];
191
            }
192
        }
193
194
        return $readonlyColumns;
195
    }
196
197
    /**
198
     * Convert Timestamp to FlexiBee Date format.
199
     *
200
     * @param int $timpestamp
201
     *
202
     * @return string FlexiBee Date or NULL
203
     */
204 17 View Code Duplication
    public static function timestampToFlexiDate($timpestamp = 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...
205
    {
206 17
        $flexiDate = null;
207 17
        if (!is_null($timpestamp)) {
208 17
            $date      = new \DateTime();
209 17
            $date->setTimestamp($timpestamp);
210 17
            $flexiDate = $date->format('Y-m-d');
211 17
        }
212 17
        return $flexiDate;
213
    }
214
215
    /**
216
     * Convert Timestamp to Flexi DateTime format.
217
     *
218
     * @param int $timpestamp
219
     *
220
     * @return string FlexiBee DateTime or NULL
221
     */
222 17 View Code Duplication
    public static function timestampToFlexiDateTime($timpestamp = 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...
223
    {
224 17
        $flexiDateTime = null;
225 17
        if (!is_null($timpestamp)) {
226 17
            $date          = new \DateTime();
227 17
            $date->setTimestamp($timpestamp);
228 17
            $flexiDateTime = $date->format('Y-m-dTH:i:s');
229 17
        }
230 17
        return $flexiDateTime;
231
    }
232
233
    /**
234
     * Add Data to evidence Branch
235
     * Přidá data do větve
236
     *
237
     * @thanksto Karel Běl
238
     *
239
     * @see Relations
240
     *
241
     * @param array  $data pole dat
242
     * @param string $relationPath path evidence (relation) pro vkládaná data
243
     *
244
     * @return boolean Operation success
245
     */
246
    public function addArrayToBranch($data, $relationPath)
247
    {
248
        if ($this->debug === true) {
249
            $relationsByUrl = \Ease\Sand::reindexArrayBy($this->getRelationsInfo(),
250
                    'url');
251
            if (!array_key_exists($relationPath, $relationsByUrl)) {
252
                $this->addStatusMessage("Relation to $relationPath does not exist for evidence ".$this->getEvidence(),
253
                    'warning');
254
            }
255
        }
256
        $currentBranchData = $this->getDataValue($relationPath);
257
        $branchData        = $currentBranchData;
258
        $branchData[]      = $data;
259
        return $this->setDataValue($relationPath, $branchData);
260
    }
261
262
    /**
263
     * Vloží do větve data z objektu
264
     *
265
     * @param FlexiBeeRO $object objekt evidence
266
     */
267
    public function addObjectToBranch($object)
268
    {
269
        $this->addArrayToBranch($object->getData(), $object->getEvidence());
270
    }
271
272
    /**
273
     * Přidá uživatelskou vazbu
274
     *
275
     * @see https://www.flexibee.eu/api/dokumentace/ref/uzivatelske-vazby/
276
     * @param string $vazba
277
     */
278
    public function vazbaAdd($vazba)
279
    {
280
        $this->addArrayToBranch(['uzivatelska-vazba' => $vazba],
281
            'uzivatelske-vazby');
282
    }
283
284
    /**
285
     * Smaže uživatelskou vazbu
286
     *
287
     * @see https://www.flexibee.eu/api/dokumentace/ref/uzivatelske-vazby/
288
     * @param string $vazba
289
     */
290
    public function vazbaDel($vazba)
291
    {
292
        $this->setDataValue('uzivatelska-vazba@action', 'delete');
293
        $this->addArrayToBranch(['uzivatelska-vazba' => $vazba],
294
            'uzivatelske-vazby');
295
    }
296
297
    /**
298
     * Převede data do Json formátu pro FlexiBee.
299
     * Pokud jsou štítky pole, jsou převedeny na seznam oddělený čárkou.
300
     * Convert data to FlexiBee like Json format.
301
     * Array of Labels is converted to coma separated list
302
     *
303
     * @param array $data
304
     *
305
     * @return string
306
     */
307
    public function jsonizeData($data)
308
    {
309
        if (array_key_exists('stitky', $data)) {
310
            if (is_array($data['stitky'])) {
311
                $data['stitky'] = implode(',', $data['stitky']);
312
            }
313
        }
314
        return parent::jsonizeData($data);
315
    }
316
317
    /**
318
     * Insert current data into FlexiBee and load actual record data back
319
     *
320
     * @return boolean Operation success
321
     */
322
    public function refresh()
323
    {
324
        $this->insertToFlexiBee();
325
        $insertResult = $this->lastResponseCode;
326
        $id           = $this->getRecordID();
327
        $this->dataReset();
328
        $this->loadFromFlexiBee($id);
329
        $loadResult   = $this->lastResponseCode;
330
        return (($insertResult == 201) && ($loadResult == 200));
331
    }
332
333
    /**
334
     * Perform given action (if availble) on current evidence/record
335
     * @url https://demo.flexibee.eu/devdoc/actions
336
     *
337
     * @param string $action one of evidence actions
338
     * @param string $method ext|int External method call operation in URL.
339
     *                               Internal add the @action element to request body
340
     *
341
     * @return boolean operation success
342
     */
343 17
    public function performAction($action, $method = 'ext')
344
    {
345 17
        $actionsAvailble = $this->getActionsInfo();
346
347 17
        if (is_array($actionsAvailble) && array_key_exists($action,
348 17
                $actionsAvailble)) {
349 15
            switch ($actionsAvailble[$action]['actionMakesSense']) {
350 15
                case 'ONLY_WITH_INSTANCE_AND_NOT_IN_EDIT':
351 15
                case 'ONLY_WITH_INSTANCE': //Add instance
352 4
                    $urlSuffix = '/'.$this->__toString().'/'.$action;
353 4
                    break;
354
355 15
                default:
356 15
                    $urlSuffix = '/'.$action;
357 15
                    break;
358 15
            }
359
360
            switch ($method) {
361 15
                case 'int':
362 4
                    $this->setAction($action);
363 4
                    $this->setPostFields($this->jsonizeData(['id' => $this]));
364 4
                    $this->performRequest(null, 'POST');
365 4
                    $result = $this->lastResponseCode == 201;
366 4
                    break;
367
368 15
                default:
369 15
                    $result = $this->performRequest($this->evidenceUrlWithSuffix($urlSuffix),
370 15
                        'GET');
371 15
                    break;
372 15
            }
373 15
        } else {
374 17
            throw new \Exception(sprintf(_('Unsupported action %s for evidence %s'),
375 17
                    $action, $this->getEvidence()));
376
        }
377
378 15
        return $result;
379
    }
380
}
381