Completed
Pull Request — master (#72)
by
unknown
04:20
created

Transaction::apiAdd()   C

Complexity

Conditions 7
Paths 12

Size

Total Lines 33
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 7.2944

Importance

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