Test Failed
Push — master ( 99a915...bca16c )
by Vítězslav
07:03
created

FlexiBeeRW::performAction()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 37
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 28
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 27
nc 7
nop 2
dl 0
loc 37
rs 8.439
c 0
b 0
f 0
ccs 28
cts 28
cp 1
crap 6
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
     * @param array  $data pole dat
239
     * @param string $relationPath path evidence (relation) pro vkládaná data 
240
     * @see Relations
241
     */
242
    public function addArrayToBranch($data, $relationPath)
243
    {
244
        if ($this->debug === true) {
245
            $relationsByUrl = \Ease\Sand::reindexArrayBy($this->getRelationsInfo(),
246
                    'url');
247
            if (!array_key_exists($relationPath, $relationsByUrl)) {
248
                $this->addStatusMessage("Relation to $relationPath does not exist for evidence ".$this->getEvidence(),
249
                    'warning');
250
            }
251
        }
252
        $currentBranchData = $this->getDataValue($relationPath);
253
        $branchData        = $currentBranchData;
254
        $branchData[]      = $data;
255
        $this->setDataValue($relationPath, $branchData);
256
    }
257
258
    /**
259
     * Vloží do větve data z objektu
260
     *
261
     * @param FlexiBeeRO $object objekt evidence
262
     */
263
    public function addObjectToBranch($object)
264
    {
265
        $this->addArrayToBranch($object->getData(), $object->getEvidence());
266
    }
267
268
    /**
269
     * Přidá uživatelskou vazbu
270
     *
271
     * @see https://www.flexibee.eu/api/dokumentace/ref/uzivatelske-vazby/
272
     * @param string $vazba
273
     */
274
    public function vazbaAdd($vazba)
275
    {
276
        $this->addArrayToBranch(['uzivatelska-vazba' => $vazba],
277
            'uzivatelske-vazby');
278
    }
279
280
    /**
281
     * Smaže uživatelskou vazbu
282
     *
283
     * @see https://www.flexibee.eu/api/dokumentace/ref/uzivatelske-vazby/
284
     * @param string $vazba
285
     */
286
    public function vazbaDel($vazba)
287
    {
288
        $this->setDataValue('uzivatelska-vazba@action', 'delete');
289
        $this->addArrayToBranch(['uzivatelska-vazba' => $vazba],
290
            'uzivatelske-vazby');
291
    }
292
293
    /**
294
     * Převede data do Json formátu pro FlexiBee.
295
     * Pokud jsou štítky pole, jsou převedeny na seznam oddělený čárkou.
296
     * Convert data to FlexiBee like Json format.
297
     * Array of Labels is converted to coma separated list
298
     *
299
     * @param array $data
300
     *
301
     * @return string
302
     */
303
    public function jsonizeData($data)
304
    {
305
        if (array_key_exists('stitky', $data)) {
306
            if (is_array($data['stitky'])) {
307
                $data['stitky'] = implode(',', $data['stitky']);
308
            }
309
        }
310
        return parent::jsonizeData($data);
311
    }
312
313
    /**
314
     * Insert current data into FlexiBee and load actual record data back
315
     *
316
     * @return boolean Operation success
317
     */
318
    public function refresh()
319
    {
320
        $this->insertToFlexiBee();
321
        $insertResult = $this->lastResponseCode;
322
        $id           = $this->getRecordID();
323
        $this->dataReset();
324
        $this->loadFromFlexiBee($id);
325
        $loadResult   = $this->lastResponseCode;
326
        return (($insertResult == 201) && ($loadResult == 200));
327
    }
328
329
    /**
330
     * Perform given action (if availble) on current evidence/record
331
     * @url https://demo.flexibee.eu/devdoc/actions
332
     *
333
     * @param string $action one of evidence actions
334
     * @param string $method ext|int External method call operation in URL.
335
     *                               Internal add the @action element to request body
336
     *
337
     * @return boolean operation success
338
     */
339 17
    public function performAction($action, $method = 'ext')
340
    {
341 17
        $actionsAvailble = $this->getActionsInfo();
342
343 17
        if (is_array($actionsAvailble) && array_key_exists($action,
344 17
                $actionsAvailble)) {
345 15
            switch ($actionsAvailble[$action]['actionMakesSense']) {
346 15
                case 'ONLY_WITH_INSTANCE_AND_NOT_IN_EDIT':
347 15
                case 'ONLY_WITH_INSTANCE': //Add instance
348 4
                    $urlSuffix = '/'.$this->__toString().'/'.$action;
349 4
                    break;
350
351 15
                default:
352 15
                    $urlSuffix = '/'.$action;
353 15
                    break;
354 15
            }
355
356
            switch ($method) {
357 15
                case 'int':
358 4
                    $this->setAction($action);
359 4
                    $this->setPostFields($this->jsonizeData(['id' => $this]));
360 4
                    $this->performRequest(null, 'POST');
361 4
                    $result = $this->lastResponseCode == 201;
362 4
                    break;
363
364 15
                default:
365 15
                    $result = $this->performRequest($this->evidenceUrlWithSuffix($urlSuffix),
366 15
                        'GET');
367 15
                    break;
368 15
            }
369 15
        } else {
370 17
            throw new \Exception(sprintf(_('Unsupported action %s for evidence %s'),
371 17
                    $action, $this->getEvidence()));
372
        }
373
374 15
        return $result;
375
    }
376
}
377