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

Transaction   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 106
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 85.29%

Importance

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