Completed
Push — master ( 6835a6...4d776f )
by Nate
12:26
created

Companies::addContact()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 41
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 41
ccs 0
cts 31
cp 0
rs 8.8571
c 0
b 0
f 0
cc 2
eloc 22
nc 2
nop 3
crap 6
1
<?php
2
3
namespace flipbox\hubspot\modules\http\services;
4
5
use Craft;
6
use craft\helpers\Json;
7
use flipbox\hubspot\authentication\AuthenticationStrategyInterface;
8
use flipbox\hubspot\cache\CacheStrategyInterface;
9
use flipbox\hubspot\HubSpot;
10
use Flipbox\Relay\HubSpot\Segment\Companies\AddContact;
11
use Flipbox\Relay\HubSpot\Segment\Companies\Create;
12
use Flipbox\Relay\HubSpot\Segment\Companies\GetByDomain;
13
use Flipbox\Relay\HubSpot\Segment\Companies\GetById;
14
use Flipbox\Relay\HubSpot\Segment\Companies\RemoveContact;
15
use Flipbox\Relay\HubSpot\Segment\Companies\UpdateById;
16
use Flipbox\Relay\HubSpot\Segment\Companies\UpdateByDomain;
17
use Psr\Http\Message\ResponseInterface;
18
19
class Companies extends AbstractResource
20
{
21
    /**
22
     * @param array                                $payload
23
     * @param AuthenticationStrategyInterface|null $authenticationStrategy
24
     * @return ResponseInterface
25
     */
26
    public function create(
27
        array $payload,
28
        AuthenticationStrategyInterface $authenticationStrategy = null
29
    ) {
30
        // Create runner segments
31
        $segments = new Create(
32
            [
33
                'payload' => $payload,
34
                'logger' => $this->getLogger()
35
            ]
36
        );
37
38
        // Prepend authorization
39
        $this->prependAuthenticationMiddleware(
40
            $segments,
41
            $authenticationStrategy
42
        );
43
44
        return $segments->run();
45
    }
46
47
    /**
48
     * @param int                                  $id
49
     * @param array                                $payload
50
     * @param AuthenticationStrategyInterface|null $authenticationStrategy
51
     * @return ResponseInterface
52
     */
53
    public function updateById(
54
        int $id,
55
        array $payload,
56
        AuthenticationStrategyInterface $authenticationStrategy = null
57
    ) {
58
        // Create runner segments
59
        $segments = new UpdateById([
60
            'id' => $id,
61
            'payload' => $payload,
62
            'logger' => $this->getLogger()
63
        ]);
64
65
        // Prepend authorization
66
        $this->prependAuthenticationMiddleware(
67
            $segments,
68
            $authenticationStrategy
69
        );
70
71
        return $segments->run();
72
    }
73
74
    /**
75
     * @param string                               $domain
76
     * @param array                                $payload
77
     * @param AuthenticationStrategyInterface|null $authenticationStrategy
78
     * @return ResponseInterface
79
     */
80
    public function updateByDomain(
81
        string $domain,
82
        array $payload,
83
        AuthenticationStrategyInterface $authenticationStrategy = null
84
    ) {
85
        // Create runner segments
86
        $segments = new UpdateByDomain([
87
            'domain' => $domain,
88
            'payload' => $payload,
89
            'logger' => $this->getLogger()
90
        ]);
91
92
        // Prepend authorization
93
        $this->prependAuthenticationMiddleware(
94
            $segments,
95
            $authenticationStrategy
96
        );
97
98
        return $segments->run();
99
    }
100
101
    /**
102
     * @param int                                  $id
103
     * @param AuthenticationStrategyInterface|null $authenticationStrategy
104
     * @param CacheStrategyInterface|null          $cacheStrategy
105
     * @return ResponseInterface
106
     */
107
    public function getById(
108
        int $id,
109
        AuthenticationStrategyInterface $authenticationStrategy = null,
110
        CacheStrategyInterface $cacheStrategy = null
111
    ) {
112
        // Create runner segments
113
        $segments = new GetById([
114
            'id' => $id,
115
            'logger' => $this->getLogger(),
116
            'cache' => $this->resolveCacheStrategy($cacheStrategy)->getPool()
117
        ]);
118
119
        // Prepend authorization
120
        $this->prependAuthenticationMiddleware(
121
            $segments,
122
            $authenticationStrategy
123
        );
124
125
        return $segments->run();
126
    }
127
128
    /**
129
     * @param string                               $domain
130
     * @param AuthenticationStrategyInterface|null $authenticationStrategy
131
     * @param CacheStrategyInterface|null          $cacheStrategy
132
     * @return ResponseInterface
133
     */
134
    public function getByDomain(
135
        string $domain,
136
        AuthenticationStrategyInterface $authenticationStrategy = null,
137
        CacheStrategyInterface $cacheStrategy = null
138
    ) {
139
        // Create runner segments
140
        $segments = new GetByDomain([
141
            'domain' => $domain,
142
            'logger' => $this->getLogger(),
143
            'cache' => $this->resolveCacheStrategy($cacheStrategy)->getPool()
144
        ]);
145
146
        // Prepend authorization
147
        $this->prependAuthenticationMiddleware(
148
            $segments,
149
            $authenticationStrategy
150
        );
151
152
        return $segments->run();
153
154
        if ($response->getStatusCode() !== 200) {
0 ignored issues
show
Unused Code introduced by
if ($response->getStatus...))); return null; } does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
155
            HubSpot::warning(
156
                Craft::t(
157
                    "Unable to get company with domain: {domain}",
158
                    [
0 ignored issues
show
Documentation introduced by
array('{domain}' => $domain) is of type array<string,?>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
159
                    '{domain}' => $domain
160
                    ]
161
                )
162
            );
163
            return null;
164
        }
165
166
        return Json::decodeIfJson($response->getBody()->getContents());
167
    }
168
169
    /**
170
     * @param int                                  $companyId
171
     * @param int                                  $contactId
172
     * @param AuthenticationStrategyInterface|null $authenticationStrategy
173
     * @return array|bool
174
     */
175
    public function addContact(
176
        int $companyId,
177
        int $contactId,
178
        AuthenticationStrategyInterface $authenticationStrategy = null
179
    ) {
180
        // Create runner segments
181
        $segments = new AddContact(
182
            [
183
                'id' => $companyId,
184
                'contactId' => $contactId,
185
                'logger' => $this->getLogger()
186
            ]
187
        );
188
189
        // Prepend authorization
190
        $this->prependAuthenticationMiddleware(
191
            $segments,
192
            $authenticationStrategy
193
        );
194
195
        // Run Http
196
        $response = $segments->run();
197
198
        // Interpret response
199
        if ($response->getStatusCode() !== 200) {
200
            $body = Json::decodeIfJson($response->getBody()->getContents());
201
202
            HubSpot::warning(
203
                sprintf(
204
                    "Unable to add contact %s to company %s, errors: %s",
205
                    $contactId,
206
                    $companyId,
207
                    Json::encode($body)
208
                )
209
            );
210
211
            return $body;
212
        }
213
214
        return true;
215
    }
216
217
    /**
218
     * @param int                                  $companyId
219
     * @param int                                  $contactId
220
     * @param AuthenticationStrategyInterface|null $authenticationStrategy
221
     * @return ResponseInterface
222
     */
223
    public function removeContact(
224
        int $companyId,
225
        int $contactId,
226
        AuthenticationStrategyInterface $authenticationStrategy = null
227
    ) {
228
        // Create runner segments
229
        $segments = new RemoveContact(
230
            [
231
                'id' => $companyId,
232
                'contactId' => $contactId,
233
                'logger' => $this->getLogger()
234
            ]
235
        );
236
237
        // Prepend authorization
238
        $this->prependAuthenticationMiddleware(
239
            $segments,
240
            $authenticationStrategy
241
        );
242
243
        return $segments->run();
244
245
        // Interpret response
246
        if ($response->getStatusCode() !== 204) {
0 ignored issues
show
Unused Code introduced by
// Interpret response if...)); return $body; } does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
247
            $body = Json::decodeIfJson($response->getBody()->getContents());
248
249
            HubSpot::warning(
250
                sprintf(
251
                    "Unable to remove contact %s from company %s, errors: %s",
252
                    $contactId,
253
                    $companyId,
254
                    Json::encode($body)
255
                )
256
            );
257
258
            return $body;
259
        }
260
261
        return true;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return true; (boolean) is incompatible with the return type documented by flipbox\hubspot\modules\...ompanies::removeContact of type Psr\Http\Message\ResponseInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
262
    }
263
}
264