Completed
Push — master ( ad5736...6d78ae )
by Maxim
03:06
created

ContactSet::buildRequest()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 30
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 15
nc 4
nop 0
1
<?php
2
3
namespace mb24dev\AmoCRM\Method;
4
5
use GuzzleHttp\Psr7\Request;
6
use mb24dev\AmoCRM\Entity\AmoEntityInterface;
7
use mb24dev\AmoCRM\Entity\AmoIdentityInterface;
8
use Psr\Http\Message\RequestInterface;
9
10
/**
11
 * Class ContactSet
12
 *
13
 * @package mb24dev\AmoCRM\Method
14
 */
15
class ContactSet extends BaseMethod
16
{
17
    /**
18
     * @var AmoEntityInterface[]
19
     */
20
    private $addContacts = [];
21
22
    /**
23
     * @var AmoEntityInterface[]
24
     */
25
    private $updateContacts = [];
26
27
    /**
28
     * @return RequestInterface
29
     */
30
    public function buildRequest()
31
    {
32
        $addContacts = [];
33
        $updateContacts = [];
34
35
        foreach ($this->addContacts as $addContact) {
36
            $addContacts[] = $addContact->toAmoArray();
37
        }
38
39
        foreach ($this->updateContacts as $updateContact) {
40
            $updateContacts[] = $updateContact->toAmoArray();
41
        }
42
43
        $body = json_encode(
44
            [
45
                'request' => [
46
                    'contacts' => [
47
                        'add' => $addContacts,
48
                        'update' => $updateContacts,
49
                    ],
50
                ],
51
            ]
52
        );
53
54
        $request = new Request(
55
            'POST', $this->getUser()->getAmoCRMDomain() . 'private/api/v2/json/contacts/set', [], $body
56
        );
57
58
        return $request;
59
    }
60
61
    /**
62
     * @return AmoEntityInterface[]
63
     */
64
    public function getContacts()
65
    {
66
        return array_merge($this->addContacts, $this->updateContacts);
67
    }
68
69
    /**
70
     * @param AmoIdentityInterface[] $contacts
71
     * @return $this
72
     */
73
    public function setContacts($contacts)
74
    {
75
        if (!is_array($contacts)) {
76
            $contacts = [$contacts];
77
        }
78
79
        foreach ($contacts as $contact) {
80
            if ($contact->getAmoID()) {
81
                $this->updateContacts[] = $contact;
82
            } else {
83
                $this->addContacts[] = $contact;
84
            }
85
        }
86
87
        return $this;
88
    }
89
90
}
91