AmoCRM   F
last analyzed

Complexity

Total Complexity 99

Size/Duplication

Total Lines 846
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 99
eloc 280
dl 0
loc 846
rs 2
c 0
b 0
f 0

30 Methods

Rating   Name   Duplication   Size   Complexity  
A getUsers() 0 3 1
A createBackupFile() 0 8 3
A getLeadNotes() 0 16 1
A searchLeads() 0 21 1
A getCustomFields() 0 5 1
A getPhoneEnums() 0 3 1
A getCustomFieldsEnums() 0 5 1
A searchContacts() 0 17 1
A getStatusesName() 0 3 1
A searchUserId() 0 13 4
A getPipelinesName() 0 3 1
A getCompanyNotes() 0 16 1
A getEmailEnums() 0 3 1
A getTaskNotes() 0 16 1
B __construct() 0 26 7
A searchTasks() 0 17 1
A backup() 0 41 1
A getContactNotes() 0 16 1
A searchPipelineId() 0 13 4
A getPhoneFieldId() 0 3 1
A searchStatusId() 0 15 4
A getTaskTypes() 0 3 1
A searchCompanies() 0 17 1
A searchStatusColor() 0 6 1
F loadInfo() 0 40 18
B searchContactsByPhoneAndEmail() 0 28 9
A getEmailFieldId() 0 3 1
A searchTaskType() 0 13 4
A isAuthorization() 0 3 1
F search() 0 105 25

How to fix   Complexity   

Complex Class

Complex classes like AmoCRM often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AmoCRM, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * Created by PhpStorm.
5
 * User: DrillCoder
6
 * Date: 21.07.17
7
 * Time: 17:11
8
 */
9
10
namespace DrillCoder\AmoCRM_Wrap;
11
12
use DateTime;
13
use DrillCoder\AmoCRM_Wrap\Helpers\Config;
14
use stdClass;
15
16
/**
17
 * Class Amo
18
 * @package DrillCoder\AmoCRM_Wrap
19
 *
20
 * @version Version 7.0.5
21
 */
22
class AmoCRM extends Base
23
{
24
    /**
25
     * Wrap Version
26
     */
27
    const VERSION = '7.0.5';
28
29
    /**
30
     * @var int
31
     */
32
    private static $phoneFieldId;
33
34
    /**
35
     * @var int
36
     */
37
    private static $emailFieldId;
38
39
    /**
40
     * @var array
41
     */
42
    private static $phoneEnums = array();
43
44
    /**
45
     *
46
     * @var array
47
     */
48
    private static $emailEnums = array();
49
50
    /**
51
     * @var array
52
     */
53
    private static $users = array();
54
55
    /**
56
     * @var array
57
     */
58
    private static $contactCustomFields = array();
59
60
    /**
61
     * @var array
62
     */
63
    private static $contactCustomFieldsEnums = array();
64
65
    /**
66
     * @var array
67
     */
68
    private static $leadCustomFields = array();
69
70
    /**
71
     * @var array
72
     */
73
    private static $leadCustomFieldsEnums = array();
74
75
    /**
76
     * @var array
77
     */
78
    private static $companyCustomFields = array();
79
80
    /**
81
     * @var array
82
     */
83
    private static $companyCustomFieldsEnums = array();
84
85
    /**
86
     * @var array
87
     */
88
    private static $pipelinesName = array();
89
90
    /**
91
     * @var array
92
     */
93
    private static $pipelinesStatusesName = array();
94
95
    /**
96
     * @var array
97
     */
98
    private static $pipelinesStatusesColor = array();
99
100
    /**
101
     * @var array
102
     */
103
    private static $taskTypes = array();
104
105
    /**
106
     * @param string $domain
107
     * @param string $userLogin
108
     * @param string $userAPIKey
109
     *
110
     * @throws AmoWrapException
111
     */
112
    public function __construct($domain, $userLogin, $userAPIKey)
113
    {
114
        if (!defined('CURL_SSLVERSION_TLSv1_2')) {
115
            define('CURL_SSLVERSION_TLSv1_2', 6);
116
        }
117
118
        Base::$domain = $domain;
119
        Base::$userLogin = $userLogin;
120
        Base::$userAPIKey = $userAPIKey;
121
122
        $userData = array(
123
            'USER_LOGIN' => $userLogin,
124
            'USER_HASH' => $userAPIKey
125
        );
126
        $result = Base::cUrl('private/api/auth.php?type=json', $userData);
127
        if ($result !== null && isset($result->response->auth) && $result->response->auth) {
128
            Base::$authorization = $result->response->auth;
129
        } else {
130
            throw new AmoWrapException('Не удалось авторизоваться');
131
        }
132
133
        $result = Base::cUrl('api/v2/account?with=custom_fields,users,pipelines,task_types');
134
        if ($result !== null && isset($result->_embedded)) {
135
            self::loadInfo($result->_embedded);
136
        } else {
137
            throw new AmoWrapException('Не удалось получить данные аккаунта');
138
        }
139
    }
140
141
    /**
142
     * @return bool
143
     */
144
    public static function isAuthorization()
145
    {
146
        return Base::$authorization;
147
    }
148
149
    /**
150
     * @return int
151
     */
152
    public static function getPhoneFieldId()
153
    {
154
        return self::$phoneFieldId;
155
    }
156
157
    /**
158
     * @return int
159
     */
160
    public static function getEmailFieldId()
161
    {
162
        return self::$emailFieldId;
163
    }
164
165
    /**
166
     * @return array
167
     */
168
    public static function getPhoneEnums()
169
    {
170
        return self::$phoneEnums;
171
    }
172
173
    /**
174
     * @return array
175
     */
176
    public static function getEmailEnums()
177
    {
178
        return self::$emailEnums;
179
    }
180
181
    /**
182
     * @return array
183
     */
184
    public static function getUsers()
185
    {
186
        return self::$users;
187
    }
188
189
    /**
190
     * @return array
191
     */
192
    public static function getPipelinesName()
193
    {
194
        return self::$pipelinesName;
195
    }
196
197
    /**
198
     * @param int $pipelineId
199
     *
200
     * @return array
201
     */
202
    public static function getStatusesName($pipelineId)
203
    {
204
        return self::$pipelinesStatusesName[$pipelineId];
205
    }
206
207
    /**
208
     * @param string $type
209
     *
210
     * @return array
211
     */
212
    public static function getCustomFields($type)
213
    {
214
        $attribute = "{$type}CustomFields";
215
216
        return self::$$attribute;
217
    }
218
219
    /**
220
     * @param string $type
221
     *
222
     * @return array
223
     */
224
    public static function getCustomFieldsEnums($type)
225
    {
226
        $attribute = "{$type}CustomFieldsEnums";
227
228
        return self::$$attribute;
229
    }
230
231
    /**
232
     * @return array
233
     */
234
    public static function getTaskTypes()
235
    {
236
        return self::$taskTypes;
237
    }
238
239
    /**
240
     * @param int|string $pipelineIdOrName
241
     *
242
     * @return int
243
     * @throws AmoWrapException
244
     */
245
    public static function searchPipelineId($pipelineIdOrName)
246
    {
247
        if (isset(self::$pipelinesName[$pipelineIdOrName])) {
248
            return $pipelineIdOrName;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $pipelineIdOrName also could return the type string which is incompatible with the documented return type integer.
Loading history...
249
        }
250
251
        foreach (self::$pipelinesName as $id => $name) {
252
            if (mb_stripos($name, $pipelineIdOrName) !== false) {
253
                return $id;
254
            }
255
        }
256
257
        throw new AmoWrapException('Воронка не найден');
258
    }
259
260
    /**
261
     * @param int|string $pipelineIdOrName
262
     * @param int|string $statusIdOrName
263
     *
264
     * @return int
265
     *
266
     * @throws AmoWrapException
267
     */
268
    public static function searchStatusId($pipelineIdOrName, $statusIdOrName)
269
    {
270
        $pipelineId = self::searchPipelineId($pipelineIdOrName);
271
272
        if (isset(self::$pipelinesStatusesName[$pipelineId][$statusIdOrName])) {
273
            return $statusIdOrName;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $statusIdOrName also could return the type string which is incompatible with the documented return type integer.
Loading history...
274
        }
275
276
        foreach (self::$pipelinesStatusesName[$pipelineId] as $id => $name) {
277
            if (mb_stripos($name, $statusIdOrName) !== false) {
278
                return $id;
279
            }
280
        }
281
282
        throw new AmoWrapException('Статус не найден');
283
    }
284
285
    /**
286
     * @param int|string $pipelineIdOrName
287
     * @param int|string $statusIdOrName
288
     *
289
     * @return string
290
     *
291
     * @throws AmoWrapException
292
     */
293
    public static function searchStatusColor($pipelineIdOrName, $statusIdOrName)
294
    {
295
        $pipelineId = self::searchPipelineId($pipelineIdOrName);
296
        $statusId = self::searchStatusId($pipelineId, $statusIdOrName);
297
298
        return self::$pipelinesStatusesColor[$pipelineId][$statusId];
299
    }
300
301
    /**
302
     * @param int|string $userIdOrName
303
     *
304
     * @return int
305
     *
306
     * @throws AmoWrapException
307
     */
308
    public static function searchUserId($userIdOrName)
309
    {
310
        if (isset(self::$users[$userIdOrName])) {
311
            return $userIdOrName;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $userIdOrName also could return the type string which is incompatible with the documented return type integer.
Loading history...
312
        }
313
314
        foreach (self::$users as $id => $name) {
315
            if (mb_stripos($name, $userIdOrName) !== false) {
316
                return $id;
317
            }
318
        }
319
320
        throw new AmoWrapException('Пользователь не найден');
321
    }
322
323
    /**
324
     * @param $taskIdOrName
325
     *
326
     * @return int
327
     *
328
     * @throws AmoWrapException
329
     */
330
    public static function searchTaskType($taskIdOrName)
331
    {
332
        if (isset(self::$taskTypes[$taskIdOrName])) {
333
            return $taskIdOrName;
334
        }
335
336
        foreach (self::$taskTypes as $id => $name) {
337
            if (mb_stripos($name, $taskIdOrName) !== false) {
338
                return $id;
339
            }
340
        }
341
342
        throw new AmoWrapException('Не удалось найти тип задачи');
343
    }
344
345
    /**
346
     * @param string $phone
347
     * @param string $email
348
     *
349
     * @return Contact[]
350
     *
351
     * @throws AmoWrapException
352
     */
353
    public function searchContactsByPhoneAndEmail($phone, $email = null)
354
    {
355
        $resultContacts = array();
356
357
        $phone = Base::onlyNumbers($phone);
358
        $contacts = $this->searchContacts($phone);
359
        if (count($contacts) > 0) {
360
            foreach ($contacts as $contact) {
361
                foreach ($contact->getPhones() as $value) {
362
                    if (mb_strpos(Base::onlyNumbers($value), Base::onlyNumbers($phone)) !== false) {
363
                        $resultContacts[$contact->getId()] = $contact;
364
                    }
365
                }
366
            }
367
        }
368
369
        $contacts = $this->searchContacts($email);
370
        if (count($contacts) > 0) {
371
            foreach ($contacts as $contact) {
372
                foreach ($contact->getEmails() as $value) {
373
                    if (mb_strpos($value, $email) !== false) {
374
                        $resultContacts[$contact->getId()] = $contact;
375
                    }
376
                }
377
            }
378
        }
379
380
        return $resultContacts;
381
    }
382
383
    /**
384
     * @param string|null      $query
385
     * @param int              $limit
386
     * @param int              $offset
387
     * @param array|string|int $responsibleUsersIdOrName
388
     * @param DateTime|null    $modifiedSince
389
     * @param bool             $isRaw
390
     *
391
     * @return Contact[]|stdClass[]
392
     *
393
     * @throws AmoWrapException
394
     */
395
    public function searchContacts(
396
        $query = null,
397
        $limit = 0,
398
        $offset = 0,
399
        $responsibleUsersIdOrName = array(),
400
        DateTime $modifiedSince = null,
401
        $isRaw = false
402
    )
403
    {
404
        return $this->search(
405
            'Contact',
406
            $query,
407
            $limit,
408
            $offset,
409
            $responsibleUsersIdOrName,
410
            $modifiedSince,
411
            $isRaw
412
        );
413
    }
414
415
    /**
416
     * @param string|null      $query
417
     * @param int              $limit
418
     * @param int              $offset
419
     * @param array|string|int $responsibleUsersIdOrName
420
     * @param DateTime|null    $modifiedSince
421
     * @param bool             $isRaw
422
     *
423
     * @return Company[]|stdClass[]
424
     *
425
     * @throws AmoWrapException
426
     */
427
    public function searchCompanies(
428
        $query = null,
429
        $limit = 0,
430
        $offset = 0,
431
        $responsibleUsersIdOrName = array(),
432
        DateTime $modifiedSince = null,
433
        $isRaw = false
434
    )
435
    {
436
        return $this->search(
437
            'Company',
438
            $query,
439
            $limit,
440
            $offset,
441
            $responsibleUsersIdOrName,
442
            $modifiedSince,
443
            $isRaw
444
        );
445
    }
446
447
    /**
448
     * @param string|null      $query
449
     * @param string|int|null  $pipelineIdOrName
450
     * @param array|string|int $statuses
451
     * @param int              $limit
452
     * @param int              $offset
453
     * @param array|string|int $responsibleUsersIdOrName
454
     * @param DateTime|null    $modifiedSince
455
     * @param bool             $isRaw
456
     *
457
     * @return Lead[]|stdClass[]
458
     *
459
     * @throws AmoWrapException
460
     */
461
    public function searchLeads(
462
        $query = null,
463
        $pipelineIdOrName = null,
464
        $statuses = array(),
465
        $limit = 0,
466
        $offset = 0,
467
        $responsibleUsersIdOrName = array(),
468
        DateTime $modifiedSince = null,
469
        $isRaw = false
470
    )
471
    {
472
        return $this->search(
473
            'Lead',
474
            $query,
475
            $limit,
476
            $offset,
477
            $responsibleUsersIdOrName,
478
            $modifiedSince,
479
            $isRaw,
480
            $pipelineIdOrName,
481
            $statuses
0 ignored issues
show
Bug introduced by
It seems like $statuses can also be of type integer and string; however, parameter $statuses of DrillCoder\AmoCRM_Wrap\AmoCRM::search() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

481
            /** @scrutinizer ignore-type */ $statuses
Loading history...
482
        );
483
    }
484
485
    /**
486
     * @param string|null      $query
487
     * @param int              $limit
488
     * @param int              $offset
489
     * @param array|string|int $responsibleUsersIdOrName
490
     * @param DateTime|null    $modifiedSince
491
     * @param bool             $isRaw
492
     *
493
     * @return Task[]|stdClass[]
494
     *
495
     * @throws AmoWrapException
496
     */
497
    public function searchTasks(
498
        $query = null,
499
        $limit = 0,
500
        $offset = 0,
501
        $responsibleUsersIdOrName = array(),
502
        DateTime $modifiedSince = null,
503
        $isRaw = false
504
    )
505
    {
506
        return $this->search(
507
            'Task',
508
            $query,
509
            $limit,
510
            $offset,
511
            $responsibleUsersIdOrName,
512
            $modifiedSince,
513
            $isRaw
514
        );
515
    }
516
517
    /**
518
     * @param int              $limit
519
     * @param int              $offset
520
     * @param array|string|int $responsibleUsersIdOrName
521
     * @param DateTime|null    $modifiedSince
522
     * @param bool             $isRaw
523
     *
524
     * @return Note[]|stdClass[]
525
     *
526
     * @throws AmoWrapException
527
     */
528
    public function getContactNotes(
529
        $limit = 0,
530
        $offset = 0,
531
        $responsibleUsersIdOrName = array(),
532
        DateTime $modifiedSince = null,
533
        $isRaw = false
534
    )
535
    {
536
        return $this->search(
537
            'Note-Contact',
538
            null,
539
            $limit,
540
            $offset,
541
            $responsibleUsersIdOrName,
542
            $modifiedSince,
543
            $isRaw
544
        );
545
    }
546
547
    /**
548
     * @param int              $limit
549
     * @param int              $offset
550
     * @param array|string|int $responsibleUsersIdOrName
551
     * @param DateTime|null    $modifiedSince
552
     * @param bool             $isRaw
553
     *
554
     * @return Note[]|stdClass[]
555
     *
556
     * @throws AmoWrapException
557
     */
558
    public function getCompanyNotes(
559
        $limit = 0,
560
        $offset = 0,
561
        $responsibleUsersIdOrName = array(),
562
        DateTime $modifiedSince = null,
563
        $isRaw = false
564
    )
565
    {
566
        return $this->search(
567
            'Note-Company',
568
            null,
569
            $limit,
570
            $offset,
571
            $responsibleUsersIdOrName,
572
            $modifiedSince,
573
            $isRaw
574
        );
575
    }
576
577
    /**
578
     * @param int              $limit
579
     * @param int              $offset
580
     * @param array|string|int $responsibleUsersIdOrName
581
     * @param DateTime|null    $modifiedSince
582
     * @param bool             $isRaw
583
     *
584
     * @return Note[]|stdClass[]
585
     *
586
     * @throws AmoWrapException
587
     */
588
    public function getLeadNotes(
589
        $limit = 0,
590
        $offset = 0,
591
        $responsibleUsersIdOrName = array(),
592
        DateTime $modifiedSince = null,
593
        $isRaw = false
594
    )
595
    {
596
        return $this->search(
597
            'Note-Lead',
598
            null,
599
            $limit,
600
            $offset,
601
            $responsibleUsersIdOrName,
602
            $modifiedSince,
603
            $isRaw
604
        );
605
    }
606
607
    /**
608
     * @param int              $limit
609
     * @param int              $offset
610
     * @param array|string|int $responsibleUsersIdOrName
611
     * @param DateTime|null    $modifiedSince
612
     * @param bool             $isRaw
613
     *
614
     * @return Note[]|stdClass[]
615
     *
616
     * @throws AmoWrapException
617
     */
618
    public function getTaskNotes(
619
        $limit = 0,
620
        $offset = 0,
621
        $responsibleUsersIdOrName = array(),
622
        DateTime $modifiedSince = null,
623
        $isRaw = false
624
    )
625
    {
626
        return $this->search(
627
            'Note-Task',
628
            null,
629
            $limit,
630
            $offset,
631
            $responsibleUsersIdOrName,
632
            $modifiedSince,
633
            $isRaw
634
        );
635
    }
636
637
    /**
638
     * @param string $directory
639
     *
640
     * @throws AmoWrapException
641
     */
642
    public function backup($directory)
643
    {
644
        $this->createBackupFile(
645
            $directory,
646
            'contacts.backup',
647
            $this->searchContacts(null, 0, 0, array(), null, true)
648
        );
649
        $this->createBackupFile(
650
            $directory,
651
            'company.backup',
652
            $this->searchCompanies(null, 0, 0, array(), null, true)
653
        );
654
        $this->createBackupFile(
655
            $directory,
656
            'leads.backup',
657
            $this->searchLeads(null, null, null, 0, 0, null, null, true)
658
        );
659
        $this->createBackupFile(
660
            $directory,
661
            'tasks.backup',
662
            $this->searchTasks(null, 0, 0, array(), null, true)
663
        );
664
        $this->createBackupFile(
665
            $directory,
666
            'notes-contacts.backup',
667
            $this->getContactNotes(0, 0, array(), null, true)
668
        );
669
        $this->createBackupFile(
670
            $directory,
671
            'notes-company.backup',
672
            $this->getCompanyNotes(0, 0, array(), null, true)
673
        );
674
        $this->createBackupFile(
675
            $directory,
676
            'notes-leads.backup',
677
            $this->getLeadNotes(0, 0, array(), null, true)
678
        );
679
        $this->createBackupFile(
680
            $directory,
681
            'notes-tasks.backup',
682
            $this->getTaskNotes(0, 0, array(), null, true)
683
        );
684
    }
685
686
    /**
687
     * @param string $directory
688
     * @param string $nameFile
689
     * @param mixed  $data
690
     *
691
     * @throws AmoWrapException
692
     */
693
    private function createBackupFile($directory, $nameFile, $data)
694
    {
695
        if (!mkdir($directory, 0777, true) && !is_dir($directory)) {
696
            throw new AmoWrapException("Директория '$directory' не может быть создана");
697
        }
698
        $f = fopen("$directory/$nameFile", 'wb+');
699
        fwrite($f, serialize($data));
0 ignored issues
show
Bug introduced by
It seems like $f can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

699
        fwrite(/** @scrutinizer ignore-type */ $f, serialize($data));
Loading history...
700
        fclose($f);
0 ignored issues
show
Bug introduced by
It seems like $f can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

700
        fclose(/** @scrutinizer ignore-type */ $f);
Loading history...
701
    }
702
703
    /**
704
     * @param string           $entityName
705
     * @param string           $query
706
     * @param integer          $limit
707
     * @param integer          $offset
708
     * @param array|string|int $responsibleUsers
709
     * @param DateTime|null    $modifiedSince
710
     * @param bool             $isRaw
711
     * @param int|string|null  $pipelineIdOrName
712
     * @param array            $statuses
713
     *
714
     * @return Company[]|Contact[]|Lead[]|Task[]|Note[]|stdClass[]
715
     *
716
     * @throws AmoWrapException
717
     */
718
    private function search(
719
        $entityName,
720
        $query = null,
721
        $limit = 0,
722
        $offset = 0,
723
        $responsibleUsers = array(),
724
        DateTime $modifiedSince = null,
725
        $isRaw = false,
726
        $pipelineIdOrName = null,
727
        $statuses = array()
728
    )
729
    {
730
        $offset = (int)$offset;
731
        $limit = (int)$limit;
732
733
        if ($responsibleUsers === null) {
0 ignored issues
show
introduced by
The condition $responsibleUsers === null is always false.
Loading history...
734
            $responsibleUsers = array();
735
        } elseif (!is_array($responsibleUsers)) {
736
            $responsibleUsers = array($responsibleUsers);
737
        }
738
739
        if ($statuses === null) {
0 ignored issues
show
introduced by
The condition $statuses === null is always false.
Loading history...
740
            $statuses = array();
741
        } elseif (!is_array($statuses)) {
0 ignored issues
show
introduced by
The condition is_array($statuses) is always true.
Loading history...
742
            $statuses = array($statuses);
743
        }
744
745
        $options = explode('-', $entityName);
746
        $className = $options[0];
747
        $type = isset($options[1]) ? mb_strtolower($options[1]) : null;
748
749
        $entityFulName = __NAMESPACE__ . "\\$className";
750
        $attribute     = mb_strtolower($className);
751
        $config        = Config::$$attribute;
752
        $url           = 'api/v2/' . $config['url'] . '?';
753
        if ($query !== null) {
754
            $url .= "&query=$query";
755
        }
756
        if ($type !== null) {
757
            $url .= "&type=$type";
758
        }
759
760
        if ($pipelineIdOrName !== null && count($statuses) > 0) {
761
            foreach ($statuses as $statusIdOrName) {
762
                $statusId = self::searchStatusId($pipelineIdOrName, $statusIdOrName);
763
                $url .= "&status[]=$statusId";
764
            }
765
        }
766
767
        if (count($responsibleUsers) > 0) {
768
            foreach ($responsibleUsers as $responsibleUserIdOrName) {
769
                $responsibleUserId = self::searchUserId($responsibleUserIdOrName);
770
                $url .= "&responsible_user_id[]=$responsibleUserId";
771
            }
772
        }
773
774
        $totalCount = $limit;
775
        $results = array();
776
777
        while (true) {
778
            if ($totalCount > 500 || $limit === 0) {
779
                $limitRows = 500;
780
            } else {
781
                $limitRows = $totalCount;
782
            }
783
784
            $res = Base::cUrl($url . "&limit_rows=$limitRows&limit_offset=$offset", array(), $modifiedSince);
785
            if ($res === null) {
786
                break;
787
            }
788
789
            $results[] = $res->_embedded->items;
790
            if ($limit !== 0) {
791
                $totalCount -= count($res->_embedded->items);
792
                if ($totalCount <= 0) {
793
                    break;
794
                }
795
            }
796
            $offset += 500;
797
        }
798
799
        $resultRaw = array();
800
        if ($isRaw) {
801
            foreach ($results as $result) {
802
                foreach ($result as $baseRaw) {
803
                    if ($isRaw) {
804
                        $resultRaw[] = $baseRaw;
805
                    }
806
                }
807
            }
808
809
            return $resultRaw;
810
        }
811
812
        $entities = array();
813
        foreach ($results as $result) {
814
            foreach ($result as $baseRaw) {
815
                /** @var BaseEntity $entity */
816
                $entity = new $entityFulName();
817
                $entity->loadInRaw($baseRaw);
818
                $entities[] = $entity;
819
            }
820
        }
821
822
        return $entities;
823
    }
824
825
    /**
826
     * @param stdClass $data
827
     */
828
    private static function loadInfo($data)
829
    {
830
        foreach ($data->users as $user) {
831
            self::$users[$user->id] = $user->name;
832
        }
833
        foreach ($data->custom_fields->contacts as $field) {
834
            self::$contactCustomFields[$field->id] = $field->name;
835
            if ($field->name === 'Телефон' && $field->is_system) {
836
                self::$phoneFieldId = $field->id;
837
                self::$phoneEnums = array_flip(json_decode(json_encode($field->enums), true));
838
            }
839
            if ($field->name === 'Email' && $field->is_system) {
840
                self::$emailFieldId = $field->id;
841
                self::$emailEnums = array_flip(json_decode(json_encode($field->enums), true));
842
            }
843
            if ($field->field_type === 4 || $field->field_type === 5) {
844
                self::$contactCustomFieldsEnums[$field->id] = json_decode(json_encode($field->enums), true);
845
            }
846
        }
847
        foreach ($data->custom_fields->leads as $field) {
848
            self::$leadCustomFields[$field->id] = $field->name;
849
            if ($field->field_type === 4 || $field->field_type === 5) {
850
                self::$leadCustomFieldsEnums[$field->id] = json_decode(json_encode($field->enums), true);
851
            }
852
        }
853
        foreach ($data->custom_fields->companies as $field) {
854
            self::$companyCustomFields[$field->id] = $field->name;
855
            if ($field->field_type === 4 || $field->field_type === 5) {
856
                self::$companyCustomFieldsEnums[$field->id] = json_decode(json_encode($field->enums), true);
857
            }
858
        }
859
        foreach ($data->pipelines as $pipeline) {
860
            self::$pipelinesName[$pipeline->id] = $pipeline->name;
861
            foreach ($pipeline->statuses as $status) {
862
                self::$pipelinesStatusesName[$pipeline->id][$status->id] = $status->name;
863
                self::$pipelinesStatusesColor[$pipeline->id][$status->id] = $status->color;
864
            }
865
        }
866
        foreach ($data->task_types as $type) {
867
            self::$taskTypes[$type->id] = $type->name;
868
        }
869
    }
870
}