Test Failed
Pull Request — master (#6)
by Vítězslav
03:51
created

FlexiBeeRW::getLastInsertedId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
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->getJsonizedData($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
     * @param int   $options json_encode options like JSON_PRETTY_PRINT etc 
305
     *
306
     * @return string
307
     */
308
    public function getJsonizedData($data = null, $options = 0)
309
    {
310
        if(is_null($data)){
311
            $data = $this->getData();
312
        }
313
        
314
        if (array_key_exists('stitky', $data)) {
315
            if (is_array($data['stitky'])) {
316
                $data['stitky'] = implode(',', $data['stitky']);
317
            }
318
        }
319
        return parent::getJsonizedData($data, $options);
320
    }
321
322
    /**
323
     * Insert current data into FlexiBee and load actual record data back
324
     *
325
     * @return boolean Operation success
326
     */
327
    public function refresh()
328
    {
329
        $this->insertToFlexiBee();
330
        $insertResult = $this->lastResponseCode;
331
        $id           = $this->getRecordID();
332
        $this->dataReset();
333
        $this->loadFromFlexiBee($id);
334
        $loadResult   = $this->lastResponseCode;
335
        return (($insertResult == 201) && ($loadResult == 200));
336
    }
337
338
    /**
339
     * Perform given action (if availble) on current evidence/record
340
     * @url https://demo.flexibee.eu/devdoc/actions
341
     *
342
     * @param string $action one of evidence actions
343 17
     * @param string $method ext|int External method call operation in URL.
344
     *                               Internal add the @action element to request body
345 17
     *
346
     * @return boolean operation success
347 17
     */
348 17
    public function performAction($action, $method = 'int')
349 15
    {
350 15
        $actionsAvailble = $this->getActionsInfo();
351 15
352 4
        if (is_array($actionsAvailble) && array_key_exists($action,
353 4
                $actionsAvailble)) {
354
            switch ($actionsAvailble[$action]['actionMakesSense']) {
355 15
                case 'ONLY_WITH_INSTANCE_AND_NOT_IN_EDIT':
356 15
                case 'ONLY_WITH_INSTANCE': //Add instance
357 15
                    $urlSuffix = '/'.$this->__toString().'/'.$action;
358 15
                    break;
359
360
                default:
361 15
                    $urlSuffix = '/'.$action;
362 4
                    break;
363 4
            }
364 4
365 4
            switch ($method) {
366 4
                case 'int':
367
                    $this->setAction($action);
368 15
                    $this->setPostFields($this->getJsonizedData(['id' => $this]));
369 15
                    $this->performRequest(null, 'POST');
370 15
                    $result = $this->lastResponseCode == 201;
371 15
                    break;
372 15
373 15
                default:
374 17
                    $result = $this->performRequest($this->evidenceUrlWithSuffix($urlSuffix),
375 17
                        'GET');
376
                    break;
377
            }
378 15
        } else {
379
            throw new \Exception(sprintf(_('Unsupported action %s for evidence %s'),
380
                    $action, $this->getEvidence()));
381
        }
382
383
        return $result;
384
    }
385
}
386