Completed
Push — master ( 751154...66b80e )
by Maxim
02:42
created

ContactsSet   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
lcom 1
cbo 4
dl 0
loc 76
ccs 0
cts 32
cp 0
rs 10
c 1
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
B buildRequest() 0 30 3
A getContacts() 0 4 1
A setContacts() 0 16 4
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 ContactsSet extends BaseMethod
16
{
17
    /**
18
     * @var AmoEntityInterface[]
19
     */
20
    private $addEntities = [];
21
22
    /**
23
     * @var AmoEntityInterface[]
24
     */
25
    private $updateEntities = [];
26
27
    /**
28
     * @return RequestInterface
29
     */
30
    public function buildRequest()
31
    {
32
        $addEntities = [];
33
        $updateEntities = [];
34
35
        foreach ($this->addEntities as $entity) {
36
            $addEntities[] = $entity->toAmoArray();
37
        }
38
39
        foreach ($this->updateEntities as $entity) {
40
            $updateEntities[] = $entity->toAmoArray();
41
        }
42
43
        $body = json_encode(
44
            [
45
                'request' => [
46
                    'contacts' => [
47
                        'add' => $addEntities,
48
                        'update' => $updateEntities,
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->addEntities, $this->updateEntities);
67
    }
68
69
    /**
70
     * @param AmoIdentityInterface[] $entities
71
     * @return $this
72
     */
73
    public function setContacts($entities)
74
    {
75
        if (!is_array($entities)) {
76
            $entities = [$entities];
77
        }
78
79
        foreach ($entities as $entity) {
80
            if ($entity->getAmoID()) {
81
                $this->updateEntities[] = $entity;
82
            } else {
83
                $this->addEntities[] = $entity;
84
            }
85
        }
86
87
        return $this;
88
    }
89
90
}
91