Completed
Push — master ( 183705...fa502a )
by dotzero
02:20
created

Customer   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 129
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 1

Test Coverage

Coverage 97.5%

Importance

Changes 0
Metric Value
wmc 12
lcom 2
cbo 1
dl 0
loc 129
ccs 39
cts 40
cp 0.975
rs 10
c 0
b 0
f 0

5 Methods

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