Completed
Push — master ( e5b10a...ef7318 )
by dotzero
02:34 queued 01:01
created

Customer::apiUpdate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

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