Completed
Push — master ( 4b260d...6e64f1 )
by dotzero
02:00
created

Transaction::apiList()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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