Client::update()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace ddlzz\AmoAPI;
4
5
use ddlzz\AmoAPI\Exception\InvalidArgumentException;
6
use ddlzz\AmoAPI\Exception\RuntimeException;
7
use ddlzz\AmoAPI\Model\ModelFactory;
8
use ddlzz\AmoAPI\Model\ModelInterface;
9
use ddlzz\AmoAPI\Request\DataSender;
10
use ddlzz\AmoAPI\Request\UrlBuilder;
11
12
/**
13
 * Class Client. The main class for interacting with amoCRM.
14
 *
15
 * @author ddlzz
16
 */
17
class Client
18
{
19
    /** @var CredentialsManager */
20
    protected $credentials;
21
22
    /** @var DataSender */
23
    protected $dataSender;
24
25
    /** @var SettingsStorage */
26
    protected $settings;
27
28
    /** @var UrlBuilder */
29
    protected $urlBuilder;
30
31
    /** @var Auth */
32
    protected $auth;
33
34
    /**
35
     * Client constructor.
36
     *
37
     * @param CredentialsManager            $credentials
38
     * @param DataSender                    $dataSender
39
     * @param \ddlzz\AmoAPI\SettingsStorage $settings
40
     */
41 9
    public function __construct(CredentialsManager $credentials, DataSender $dataSender, SettingsStorage $settings)
42
    {
43 9
        $this->credentials = $credentials;
44 9
        $this->dataSender = $dataSender;
45 9
        $this->settings = $settings;
46 9
        $this->urlBuilder = new UrlBuilder($this->settings, $this->credentials->getSubdomain()); // Composition
47 9
        $this->auth = new Auth($this->credentials->getLogin(), $this->settings->getCookiePath());
48
49 9
        $this->checkAuth();
50 8
    }
51
52
    /**
53
     * @param $type
54
     * @param $id
55
     *
56
     * @throws InvalidArgumentException
57
     *
58
     * @return ModelInterface
59
     */
60 2
    public function findById($type, $id)
61
    {
62 2
        $method = $this->settings->getMethodCodeByType($type);
63 2
        $params = ['id' => $id];
64 2
        $url = $this->urlBuilder->buildMethodUrl($method, $params);
65 2
        $result = json_decode($this->dataSender->send($url), true);
66
67 2
        if (empty($result)) {
68 1
            throw new InvalidArgumentException("The $type with id $id is not found on the server");
69
        }
70
71 1
        $entityFactory = new ModelFactory($this->settings);
72
        /** @var ModelInterface $entity */
73 1
        $entity = $entityFactory->create($type);
74 1
        $entity->fill($result['_embedded']['items'][0]);
75
76 1
        return $entity;
77
    }
78
79
    /**
80
     * @param ModelInterface $entity
81
     *
82
     * @return string
83
     */
84 2
    public function add(ModelInterface $entity)
85
    {
86 2
        return $this->set($entity, 'add');
87
    }
88
89
    /**
90
     * @param ModelInterface $entity
91
     *
92
     * @return string
93
     */
94 1
    public function update(ModelInterface $entity)
95
    {
96 1
        $entity->setUpdatedAt();
97
98 1
        return $this->set($entity, 'update');
99
    }
100
101
    /**
102
     * @throws RuntimeException
103
     */
104 9
    protected function checkAuth()
105
    {
106 9
        if (!$this->auth->isAuthenticated()) {
107 3
            $result = $this->dataSender->send($this->urlBuilder->buildMethodUrl('auth'), $this->credentials->getCredentials());
108
109 3
            if (!empty($result) && (!file_exists($this->settings->getCookiePath()))) {
110 1
                $message = 'An error occurred while creating the cookie file '.$this->settings->getCookiePath();
111 1
                throw new RuntimeException($message);
112
            }
113
        }
114 8
    }
115
116
    /**
117
     * Adds or updates an entity.
118
     *
119
     * @param ModelInterface $entity
120
     * @param string         $action
121
     *
122
     * @return string
123
     */
124 3
    protected function set(ModelInterface $entity, $action)
125
    {
126 3
        $entity->setFields($action);
127
128 3
        $data = [];
129 3
        $data[$action][] = $entity->getFields();
130 3
        $url = $this->urlBuilder->buildMethodUrl($entity->getRequestName());
131 3
        $this->waitASec();
132
133 3
        return $this->dataSender->send($url, $data);
134
    }
135
136
    /**
137
     * Adds a one second pause because of Amo request limits.
138
     */
139 3
    protected function waitASec()
140
    {
141 3
        $now = microtime(true);
142 3
        static $lastCheck = null;
143
144 3
        if (null !== $lastCheck) {
145 2
            $sleepTime = 1;
146 2
            $lastRequest = $now - $lastCheck;
147 2
            if ($lastRequest < $sleepTime) {
148 2
                usleep(($sleepTime - $lastRequest) * 1000000);
149
            }
150
        }
151
152 3
        $lastCheck = microtime(true);
153 3
    }
154
155
    /**
156
     * Provides some info about current account and its custom fields ids.
157
     *
158
     * @return string
159
     */
160
    public function accountInfo()
161
    {
162
        $url = $this->urlBuilder->buildMethodUrl('current');
163
        return $this->dataSender->send($url, []);
164
    }
165
}
166