Completed
Pull Request — master (#72)
by
unknown
02:19
created

Customer   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 107
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 88.57%

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 4
dl 0
loc 107
ccs 31
cts 35
cp 0.8857
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A apiList() 0 6 2
B apiAdd() 0 33 7
A apiUpdate() 0 19 2
1
<?php
2
3
namespace AmoCRM\Models;
4
5
use AmoCRM\Exception;
6
use AmoCRM\Models\Traits\SetTags;
7
use AmoCRM\Models\Traits\SetNextDate;
8
9
/**
10
 * Class Customer
11
 *
12
 * Класс модель для работы с Покупателями
13
 *
14
 * @package AmoCRM\Models
15
 * @author dotzero <[email protected]>
16
 * @link http://www.dotzero.ru/
17
 * @link https://github.com/dotzero/amocrm-php
18
 *
19
 * For the full copyright and license information, please view the LICENSE
20
 * file that was distributed with this source code.
21
 */
22
class Customer extends AbstractModel
23
{
24
    use SetTags, SetNextDate;
25
26
    /**
27
     * @var array Список доступный полей для модели (исключая кастомные поля)
28
     */
29
    protected $fields = [
30
        'name',
31
        'main_user_id',
32
        'created_by',
33
        'next_price',
34
        'periodicity',
35
        'tags',
36
        'next_date',
37
        'request_id',
38
    ];
39
40
    /**
41
     * Список покупателей
42
     *
43
     * Метод для получения покупателей аккаунта
44
     *
45
     * @link https://developers.amocrm.ru/rest_api/customers/list.php
46
     * @param array $parameters Массив параметров к amoCRM API
47
     * @return array Ответ amoCRM API
48
     */
49 1
    public function apiList($parameters)
50
    {
51 1
        $response = $this->getRequest('/private/api/v2/json/customers/list', $parameters);
52
53 1
        return isset($response['customers']) ? $response['customers'] : [];
54
    }
55
56
    /**
57
     * Добавление покупателей
58
     *
59
     * Метод позволяет добавлять покупателей по одному или пакетно
60
     *
61
     * @link https://developers.amocrm.ru/rest_api/customers/set.php
62
     * @param array $customers Массив покупателей для пакетного добавления
63
     * @return int|array Уникальный идентификатор покупателя или массив при пакетном добавлении
64
     */
65 1
    public function apiAdd($customers = [])
66
    {
67 1
        if (empty($customers)) {
68 1
            $customers = [$this];
69 1
        }
70
71
        $parameters = [
72
            'customers' => [
73 1
                'add' => [],
74 1
            ],
75 1
        ];
76
77 1
        foreach ($customers AS $customer) {
78 1
            $parameters['customers']['add'][] = $customer->getValues();
79 1
        }
80
81 1
        $response = $this->postRequest('/private/api/v2/json/customers/set', $parameters);
82
83 1
        if (isset($response['customers']['add'])) {
84 1
            $result = array_map(function ($item) {
85 1
				if(!empty($item['id']))
86 1
					return $item['id'];
87
				elseif(!empty($item['error']))
88
					throw new Exception($item['error'],filter_var(mb_strstr($item['error'],".",true), FILTER_SANITIZE_NUMBER_INT));
89
				else
90
					return [];
91 1
            }, $response['customers']['add']['customers']);
92 1
        } else {
93
            return [];
94
        }
95
96 1
        return count($customers) == 1 ? array_shift($result) : $result;
97
    }
98
99
    /**
100
     * Обновление покупателей
101
     *
102
     * Метод позволяет обновлять данные по уже существующим покупателям
103
     *
104
     * @link https://developers.amocrm.ru/rest_api/customers/set.php
105
     * @param int $id Уникальный идентификатор покупателя
106
     * @return bool Флаг успешности выполнения запроса
107
     * @throws \AmoCRM\Exception
108
     */
109 1
    public function apiUpdate($id)
110
    {
111 1
        $this->checkId($id);
112
113
        $parameters = [
114
            'customers' => [
115 1
                'update' => [],
116 1
            ],
117 1
        ];
118
119 1
        $customer = $this->getValues();
120 1
        $customer['id'] = $id;
121
122 1
        $parameters['customers']['update'][] = $customer;
123
124 1
        $response = $this->postRequest('/private/api/v2/json/customers/set', $parameters);
125
126 1
        return isset($response['customers']) ? true : false;
127
    }
128
}
129