AmoCRMClient::auth()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 2.0008

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 16
cts 17
cp 0.9412
rs 9.552
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2.0008
1
<?php
2
3
namespace mb24dev\AmoCRM;
4
5
use Dflydev\FigCookies\Cookie;
6
use Dflydev\FigCookies\FigRequestCookies;
7
use Dflydev\FigCookies\SetCookies;
8
use GuzzleHttp\ClientInterface;
9
use GuzzleHttp\Psr7\Request;
10
use mb24dev\AmoCRM\HttpClient\HttpClientInterface;
11
use mb24dev\AmoCRM\Method\MethodInterface;
12
use mb24dev\AmoCRM\ResponseTransformer\ResponseTransformerInterface;
13
use mb24dev\AmoCRM\Session\Session;
14
use mb24dev\AmoCRM\Session\SessionCookieDoNotPresented;
15
use mb24dev\AmoCRM\Session\SessionDoesNotExistException;
16
use mb24dev\AmoCRM\SessionStorage\SessionStorageInterface;
17
use mb24dev\AmoCRM\User\UserInterface;
18
use Psr\Log\LoggerInterface;
19
20
/**
21
 * Class AmoCRM
22
 *
23
 * @package mb24dev\AmoCRM
24
 */
25
class AmoCRMClient
26
{
27
    /**
28
     * @var HttpClientInterface
29
     */
30
    private $httpClient;
31
32
    /**
33
     * @var SessionStorageInterface
34
     */
35
    private $sessionStorage;
36
37
    /**
38
     * @var LoggerInterface
39
     */
40
    private $logger;
41
42
    /**
43
     * @var ResponseTransformerInterface
44
     */
45
    private $responseTransformer;
46
47
    /**
48
     * AmoCRM constructor.
49
     *
50
     * @param HttpClientInterface|ClientInterface $httpClient
51
     * @param SessionStorageInterface             $sessionStorage
52
     * @param ResponseTransformerInterface        $responseTransformer
53
     * @param LoggerInterface                     $logger
54
     */
55 4
    public function __construct(
56
        $httpClient,
57
        SessionStorageInterface $sessionStorage,
58
        ResponseTransformerInterface $responseTransformer,
59
        LoggerInterface $logger = null
60
    ) {
61 4
        $this->httpClient = $httpClient;
0 ignored issues
show
Documentation Bug introduced by
It seems like $httpClient can also be of type object<GuzzleHttp\ClientInterface>. However, the property $httpClient is declared as type object<mb24dev\AmoCRM\Ht...nt\HttpClientInterface>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
62 4
        $this->responseTransformer = $responseTransformer;
63 4
        $this->sessionStorage = $sessionStorage;
64 4
        $this->logger = $logger;
65 4
    }
66
67
    /**
68
     * @param HttpClientInterface $httpClient
69
     */
70
    public function setHttpClient($httpClient)
71
    {
72
        $this->httpClient = $httpClient;
73
    }
74
75
    /**
76
     * @param SessionStorageInterface $sessionStorage
77
     */
78
    public function setSessionStorage($sessionStorage)
79
    {
80
        $this->sessionStorage = $sessionStorage;
81
    }
82
83
    /**
84
     * @param ResponseTransformerInterface $responseTransformer
85
     */
86
    public function setResponseTransformer($responseTransformer)
87
    {
88
        $this->responseTransformer = $responseTransformer;
89
    }
90
91
    /**
92
     * @param LoggerInterface $logger
93
     */
94
    public function setLogger($logger)
95
    {
96
        $this->logger = $logger;
97
    }
98
99
    /**
100
     * @param MethodInterface $method
101
     * @return mixed
102
     * @throws AmoCRMException
103
     */
104 4
    public function exec(MethodInterface $method)
105
    {
106
        try {
107 4
            $request = $method->buildRequest();
108
109 4
            if (!$session = $method->getUser()->getAmoCRMSession()) {
110 4
                $session = $this->sessionStorage->getActive($method->getUser());
111 2
            }
112
113 3
            $cookie = new Cookie('session_id', $session->getId());
114 3
            $request = FigRequestCookies::set($request, $cookie);
115
116 3
            $response = $this->httpClient->send($request);
117 4
        } catch (SessionDoesNotExistException $e) {
118 2
            $this->auth($e->getUser());
119
120 1
            return $this->exec($method);
121
        } catch (\Exception $e) {
122
            if ($this->logger) {
123
                $this->logger->critical('Client error', ['exception' => $e]);
124
            }
125
126
            throw new AmoCRMException($e->getMessage());
127
        }
128
129 3
        $methodResponseTransformer = $method->getResponseTransformer();
130
131 3
        if ($methodResponseTransformer) {
132 1
            return $methodResponseTransformer->transform($response);
133 2
        } elseif ($this->responseTransformer) {
134 2
            return $this->responseTransformer->transform($response);
135
        }
136
137
        return $response->getBody()->getContents();
138
    }
139
140
    /**
141
     * @param UserInterface $user
142
     * @throws AmoCRMException
143
     */
144 2
    private function auth(UserInterface $user)
145
    {
146 2
        $request = new Request(
147 2
            'POST', $user->getAmoCRMDomain() . "private/api/auth.php?type=json", [], \GuzzleHttp\json_encode(
148
                [
149 2
                    'USER_LOGIN' => $user->getAmoCRMLogin(),
150 2
                    'USER_HASH' => $user->getAmoCRMHash(),
151
                ]
152 2
            )
153 2
        );
154
155 2
        $response = $this->httpClient->send($request);
156 2
        $cookies = SetCookies::fromResponse($response);
157 2
        $sessionCookie = $cookies->get('session_id');
158
159 2
        if ($sessionCookie) {
160 2
            $session = new Session($sessionCookie->getValue());
161 2
            $user->setAmoCRMSession($session);
162 2
            $this->sessionStorage->save($session, $user);
163 1
        } else {
164
            throw new SessionCookieDoNotPresented();
165
        }
166 1
    }
167
}
168