Completed
Pull Request — 1.1 (#29)
by
unknown
05:23
created

Response::parseResponse()   D

Complexity

Conditions 19
Paths 16

Size

Total Lines 86
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 86
rs 4.764
c 0
b 0
f 0
cc 19
eloc 44
nc 16
nop 0

How to fix   Long Method    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
namespace Wabel\Zoho\CRM\Request;
4
5
use Wabel\Zoho\CRM\Exception\ZohoCRMException;
6
7
/**
8
 * Zoho CRM API Response.
9
 *
10
 * Parses the ZohoCRM response into an object and
11
 * normalizes different response formats.
12
 *
13
 * @version 1.0.0
14
 */
15
class Response
16
{
17
    /**
18
   * Code error.
19
   *
20
   * @var string
21
   */
22
  protected $code;
23
24
  /**
25
   * Message of the error.
26
   *
27
   * @var string
28
   */
29
  protected $message;
30
31
  /**
32
   * Method used.
33
   *
34
   * @var string
35
   */
36
  protected $method;
37
38
  /**
39
   * Module used.
40
   *
41
   * @var string
42
   */
43
  protected $module;
44
45
  /**
46
   * Records details affecteds.
47
   *
48
   * @var array
49
   */
50
  protected $records = array();
51
52
  /**
53
   * Specific redord affected.
54
   *
55
   * @var string
56
   */
57
  protected $recordId;
58
59
  /**
60
   * @var string[]
61
   */
62
  protected $deletedIds;
63
64
  /**
65
   * URL used for the request.
66
   *
67
   * @var string
68
   */
69
  protected $uri;
70
71
  /**
72
   * XML on request.
73
   *
74
   * @var string
75
   */
76
  protected $xmlstr;
77
78
  /**
79
   * File joined with response.
80
   *
81
   * @var string
82
   */
83
  protected $file;
84
85
  /**
86
   * All fields[attributes] for users.
87
   *
88
   * @var array
89
   */
90
  protected$userFields = array();
91
  
92
    public function __construct($xmlstr, $module, $method)
93
    {
94
        $this->xmlstr = $xmlstr;
95
        $this->module = $module;
96
        $this->method = $method;
97
        $this->parseResponse();
98
    }
99
100
  /**
101
   * Setters & Getters.
102
   */
103
  public function getModule()
104
  {
105
      return $this->module;
106
  }
107
108
    public function getMessage()
109
    {
110
        return $this->message;
111
    }
112
113
    public function getCode()
114
    {
115
        return $this->code;
116
    }
117
118
    public function getRequestURI()
119
    {
120
        return $this->uri;
121
    }
122
123
    public function getRecords()
124
    {
125
        return $this->records;
126
    }
127
128
    public function getRelatedRecords()
129
    {
130
        return $this->records;
131
    }
132
133
    public function getRecordId()
134
    {
135
        return $this->recordId;
136
    }
137
138
    public function getXML()
139
    {
140
        return $this->xmlstr;
141
    }
142
143
    public function getFile()
144
    {
145
        return $this->file;
146
    }
147
148
    public function getResponse()
149
    {
150
        return array(
151
      'module' => $this->module,
152
      'method' => $this->method,
153
      'message' => $this->message,
154
      'code' => $this->code,
155
      'uri' => $this->uri,
156
      'recordId' => $this->recordId,
157
      'records' => $this->records,
158
      'xmlstr' => $this->xmlstr,
159
      'file' => $this->file,
160
    );
161
    }
162
163
    /**
164
     * @return \string[]
165
     */
166
    public function getDeletedIds()
167
    {
168
        return $this->deletedIds;
169
    }
170
171
    protected function parseResponse()
172
    {
173
        if ($this->method == 'downloadFile') {
174
            $this->file = $this->xmlstr;
175
            $this->xmlstr = null;
176
        } else {
177
            $xml = simplexml_load_string($this->xmlstr, 'SimpleXMLElement', LIBXML_NOERROR | LIBXML_NOWARNING);
178
            if ($xml === false) {
179
                throw new ZohoCRMException('Zoho CRM response could not be parsed as XML.', 0000);
180
            }
181
182
            if (isset($xml->error)) {
183
                $message = (string) $xml->error->message;
184
                $code = (string) $xml->error->code;
185
                throw new ZohoCRMException($message, $code);
186
            }
187
188
            $this->uri = (string) $xml['uri'];
189
190
      // No records returned
191
      if (isset($xml->nodata)) {
192
          $this->message = (string) $xml->nodata->message;
193
          $this->code = (string) $xml->nodata->code;
194
      }
195
196
      // getFields
197
      elseif ($this->method == 'getFields') {
198
          $this->parseResponseGetFields($xml);
199
      }
200
201
      // getUsers
202
      elseif ($this->method == 'getUsers') {
203
          $this->parseResponseGetUsers($xml);
204
      }
205
206
      // getModules
207
      elseif ($this->method == 'getModules') {
208
          $this->parseResponseGetModules($xml);
209
      } elseif ($this->method == 'getDeletedRecordIds') {
210
          $deletedIdsString = (string) $xml->result->DeletedIDs;
211
          $this->deletedIds = explode(',', $deletedIdsString);
212
213
      // getRecords, getRelatedRecords, getSearchRecords, getRecordById, getCVRecords
214
      } elseif (isset($xml->result->{$this->module})) {
215
          $this->parseResponseGetRecords($xml);
216
      }
217
218
      // insertRecords, updateRecords (version = 1 or 2)
0 ignored issues
show
Unused Code Comprehensibility introduced by
36% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
219
      elseif (isset($xml->result->message) && isset($xml->result->recorddetail)) {
220
          $this->parseResponsePostRecords($xml);
221
      }
222
223
      // insertRecords, updateRecords (version = 4)
224
      elseif (isset($xml->result->row->success) || isset($xml->result->row->error)) {
225
          $this->parseResponsePostRecordsMultiple($xml);
226
      }
227
228
      // convertLead
229
      elseif ((string) $xml->getName() == 'success') {
230
          $records = array();
231
          foreach ($xml->children() as $child) {
232
              $records[(string) $child->getName()] = (string) $child;
233
          }
234
          $this->records = $records;
235
      }
236
237
      // deleteRecords
238
      elseif (isset($xml->result->message) && isset($xml->result->code)) {
239
          $this->message = (string) $xml->result->message;
240
          $this->code = (string) $xml->result->code;
241
          //preg_match('/[0-9]{18}/', $this->message, $matches);
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
242
          //$this->recordId = $matches[0];
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
243
      }
244
      
245
      // updateRelatedRecords
246
      elseif (isset($xml->result->success->code)) {
247
          $this->code = (string) $xml->result->success->code;
248
          $this->message = 'success';		// We use this string below to determine the successfulness of the call
249
      }
250
251
      // downloadFile
252
      else {
253
          throw new ZohoCRMException('Unknown Zoho CRM response format');
254
      }
255
        }
256
    }
257
258
    protected function parseResponseGetFields($xml)
259
    {
260
        $records = array();
261
        foreach ($xml->section as $section) {
262
            foreach ($section->children() as $field) {
263
                $label = (string) $field['label'];
264
                $records[(string) $section['name']][$label] = array(
265
          'req' => (string) $field['req'] === 'true' ? true : false,
266
          'type' => (string) $field['type'],
267
          'isreadonly' => (string) $field['isreadonly'] === 'true' ? true : false,
268
          'maxlength' => (int) $field['maxlength'],
269
          'label' => $label,
270
          'dv' => (string) $field['dv'],
271
          'customfield' => (string) $field['customfield'] === 'true' ? true : false,
272
        );
273
                if ($field->children()->count() > 0) {
274
                    $records[(string) $section['name']][$label]['values'] = array();
275
                    foreach ($field->children() as $value) {
276
                        $records[(string) $section['name']][$label]['values'][] = (string) $value;
277
                    }
278
                }
279
            }
280
        }
281
        $this->records = $records;
282
    }
283
284
    protected function parseResponseGetUsers($xml)
285
    {
286
        $records = array();
287
        $this->userFields[] = 'name';
288
        foreach ($xml as $user) {
289
            foreach ($user->attributes() as $key => $value) {
290
                $records[(string) $user['id']][$key] = (string) $value;
291
                if(!in_array($key,$this->userFields)){
292
                    $this->userFields[] = $key;
293
                }
294
            }
295
            $records[(string) $user['id']]['name'] = (string) $user;
296
        }
297
        $this->records = $records;
298
    }
299
300
    public function getUserFields (){
301
        return $this->userFields;
302
    }
303
304
    protected function parseResponseGetModules($xml)
305
    {
306
        $records = array();
307
        foreach ($xml->result->children() as $row) {
308
            $no = (string) $row['no'];
309
            $pl = (string) $row['pl'];
310
            $sl = (string) $row['sl'];
311
            $records[$no] = array(
312
                'key' => (string) $row,
313
                'pl' => $pl,
314
                'sl' => $sl,
315
            );
316
        }
317
        $this->records = $records;
318
    }
319
320
    protected function parseResponseGetRecords($xml)
321
    {
322
        $records = array();
323
        foreach ($xml->result->children()->children() as $row) {
324
            $no = (string) $row['no'];
325
            foreach ($row->children() as $field) {
326
                if ($field->count() > 0) {
327
                    foreach ($field->children() as $item) {
328
                        foreach ($item->children() as $subitem) {
329
                            $records[$no][(string) $field['val']][(string) $item['no']][(string) $subitem['val']] = (string) $subitem;
330
                        }
331
                    }
332
                } else {
333
                    $records[$no][(string) $field['val']] = (string) $field;
334
                }
335
            }
336
        }
337
        $this->records = $records;
338
339
        if ($this->method == 'getRecordById') {
340
            $id = strtoupper(substr($this->module, 0, -1)).'ID';
341
            if (!isset($this->records[1][$id])) {
342
                $id = strtoupper($this->module).'_ID';
343
            }
344
            $this->recordId = $this->records[1][$id];
345
        }
346
    }
347
348
    protected function parseResponsePostRecords($xml)
349
    {
350
        $record = array();
351
        foreach ($xml->result->recorddetail as $detail) {
352
            foreach ($detail->children() as $field) {
353
                $record[(string) $field['val']] = (string) $field;
354
            }
355
            $this->records[] = $record;
356
        }
357
358
        $this->message = (string) $xml->result->message;
359
        if (count($this->records) == 1) {
360
            $this->recordId = isset($record['Id']) ? $record['Id'] : null;
361
        }
362
    }
363
364
    protected function parseResponsePostRecordsMultiple($xml)
365
    {
366
        $records = array();
367
        foreach ($xml->result->row as $row) {
368
            $no = (string) $row['no'];
369
            if (isset($row->success)) {
370
                $records[$no]['code'] = (string) $row->success->code;
371
                foreach ($row->success->details->children() as $field) {
372
                    $records[$no][(string) $field['val']] = (string) $field;
373
                }
374
            } else {
375
                $records[$no]['code'] = (string) $row->error->code;
376
                $records[$no]['message'] = (string) $row->error->details;
377
            }
378
        }
379
        ksort($records);
380
        $this->records = $records;
381
    }
382
383
    public function ifSuccess()
384
    {
385
        if (strpos($this->message, 'success') !== false || !$this->code) {
386
            return true;
387
        }
388
389
        return false;
390
    }
391
}
392