Completed
Push — master ( 417a27...225bfd )
by Vítězslav
07:56
created

FlexiBeeRW::takeData()   D

Complexity

Conditions 10
Paths 3

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 17
nc 3
nop 1
dl 0
loc 29
rs 4.8196
c 1
b 0
f 0

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,2016 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
    public function insertToFlexiBee($data = null)
56
    {
57
        $info = $this->getEvidenceInfo();
58
        switch ($info['importStatus']) {
59
            case 'DISALLOWED':
60
                throw new \Exception(sprintf('Inserting data to r/o evidence %s',
61
                    $this->getEvidence()));
62
            case 'NOT_DIRECT':
63
                throw new \Exception(sprintf('Inserting data to slave only evidence %s',
64
                    $this->getEvidence()));
65
            case 'NOT_DOCUMENTED':
66
                if ($this->debug === true) {
67
                    $this->addStatusMessage(sprintf('Inserting data to undocumneted evidence %s',
68
                            $this->getEvidence()));
69
                }
70
71
                break;
72
            case 'SUPPORTED':
73
            default:
74
                break;
75
        }
76
77
        if (is_null($data)) {
78
            $data = $this->getData();
79
        }
80
        if ($this->debug === true) {
81
            $missingColumns = $this->controlMandatoryColumns();
82
            if (count($missingColumns)) {
83
                $this->addStatusMessage(sprintf('Given data does not contain requied Columns: %s',
84
                        implode(',', $missingColumns))
85
                    , 'warning');
86
            }
87
        }
88
        $this->postFields = $this->jsonizeData($data);
89
        return $this->performRequest($this->evidence.'.'.$this->format, 'PUT');
90
    }
91
92
    /**
93
     * Give you last inserted record ID.
94
     * 
95
     * @return int
96
     */
97
    public function getLastInsertedId()
98
    {
99
        return $this->lastInsertedID;
100
    }
101
102
    /**
103
     * Smaže záznam
104
     * Delete record in FlexiBee
105
     *
106
     * @param int|string $id identifikátor záznamu
107
     * @return boolean Response code is 200 ?
108
     */
109
    public function deleteFromFlexiBee($id = null)
110
    {
111
        if (is_null($id)) {
112
            $id = $this->getMyKey();
113
        }
114
        $this->performRequest($this->evidence.'/'.$id.'.'.$this->format,
115
            'DELETE');
116
        return $this->lastResponseCode == 200;
117
    }
118
119
    /**
120
     * Control for existing column names in evidence and take data
121
     *
122
     * @param array $data Data to keep
123
     * @return int number of records taken
124
     */
125
    public function takeData($data)
126
    {
127
        if ($this->debug === true) {
128
            $fbColumns   = $this->getColumnsInfo();
129
            foreach ($this->getRelationsInfo() as $relation) {
130
                if (is_array($relation) && isset($relation['url'])) {
131
                    $fbRelations[$relation['url']] = $relation['url'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$fbRelations was never initialized. Although not strictly required by PHP, it is generally a good practice to add $fbRelations = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
132
                }
133
            }
134
135
            if (count($fbColumns)) {
136
                foreach ($data as $key => $value) {
137
                    if (!array_key_exists($key, $fbColumns)) {
138
139
                        if (!array_key_exists($key, $fbRelations)) {
0 ignored issues
show
Bug introduced by
The variable $fbRelations 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...
140
                            $this->addStatusMessage(sprintf('unknown column %s for evidence %s',
141
                                    $key, $this->getEvidence()), 'warning');
142
                        } else {
143
                            if (!is_array($value)) {
144
                                $this->addStatusMessage(sprintf('subevidence %s in evidence %s must bee an array',
145
                                        $key, $this->getEvidence()), 'warning');
146
                            }
147
                        }
148
                    }
149
                }
150
            }
151
        }
152
        return parent::takeData($data);
153
    }
154
155
    /**
156
     * Control data for mandatory columns presence.
157
     *
158
     * @param array $data
159
     * @return array List of missing columns. Empty if all is ok
160
     */
161 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...
162
    {
163
        if (is_null($data)) {
164
            $data = $this->getData();
165
        }
166
167
        $missingMandatoryColumns = [];
168
169
        $fbColumns   = $this->getColumnsInfo();
170
        foreach ($fbColumns as $columnName => $columnInfo) {
171
            $mandatory = ($columnInfo['mandatory'] == 'true');
172
            if ($mandatory && !array_key_exists($columnName, $data)) {
173
                $missingMandatoryColumns[$columnName] = $columnInfo['name'];
174
            }
175
        }
176
177
        return $missingMandatoryColumns;
178
    }
179
180
    /**
181
     * Control data for readonly columns presence.
182
     *
183
     * @param array $data
184
     * @return array List of ReadOnly columns. Empty if all is ok
185
     */
186 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...
187
    {
188
        if (is_null($data)) {
189
            $data->getData();
0 ignored issues
show
Bug introduced by
The method getData cannot be called on $data (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
190
        }
191
192
        $readonlyColumns = [];
193
194
        $fbColumns = $this->getColumnsInfo();
195
        foreach ($fbColumns as $columnName => $columnInfo) {
196
            $writable = ($columnInfo['isWritable'] == 'true');
197
            if (!$writable && !array_key_exists($columnName, $data)) {
198
                $readonlyColumns[$columnName] = $columnInfo['name'];
199
            }
200
        }
201
202
        return $readonlyColumns;
203
    }
204
205
    /**
206
     * Convert Timestamp to FlexiBee Date format.
207
     *
208
     * @param int $timpestamp
209
     *
210
     * @return string FlexiBee Date or NULL
211
     */
212 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...
213
    {
214
        $flexiDate = null;
215
        if (!is_null($timpestamp)) {
216
            $date      = new \DateTime();
217
            $date->setTimestamp($timpestamp);
218
            $flexiDate = $date->format('Y-m-d');
219
        }
220
        return $flexiDate;
221
    }
222
223
    /**
224
     * Convert Timestamp to Flexi DateTime format.
225
     *
226
     * @param int $timpestamp
227
     *
228
     * @return string FlexiBee DateTime or NULL
229
     */
230 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...
231
    {
232
        $flexiDateTime = null;
233
        if (!is_null($timpestamp)) {
234
            $date          = new \DateTime();
235
            $date->setTimestamp($timpestamp);
236
            $flexiDateTime = $date->format('Y-m-dTH:i:s');
237
        }
238
        return $flexiDateTime;
239
    }
240
241
}
242