Passed
Push — develop ( eacc0b...67462a )
by Andrew
02:45
created

Client::set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

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