Completed
Push — 1.0 ( f2f1ab...d8cbdb )
by Raphaël
10s
created

Response::getUserFields()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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