Completed
Pull Request — 2.1 (#1090)
by Paweł
09:07
created

AppleNewsApi   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 112
Duplicated Lines 16.07 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 5
dl 18
loc 112
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A createArticle() 9 9 1
A updateArticle() 9 9 1
A deleteArticle() 0 9 1
A generateData() 0 25 2
A generateHhmacSignature() 0 7 1
A getAuthorizationSignature() 0 10 1
A getContentType() 0 4 1
A post() 0 13 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Web Publisher Core Bundle.
7
 *
8
 * Copyright 2020 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2020 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\CoreBundle\AppleNews\Api;
18
19
use GuzzleHttp\Client;
20
use GuzzleHttp\Psr7\MultipartStream;
21
use Psr\Http\Message\ResponseInterface;
22
use SWP\Bundle\CoreBundle\AppleNews\Api\Response\AppleNewsArticle;
23
24
final class AppleNewsApi
25
{
26
    private $httpClient;
27
28
    private $apiKeyId;
29
30
    private $apiKeySecret;
31
32
    private $boundary;
33
34
    public function __construct(Client $httpClient, string $apiKeyId, string $apiKeySecret)
35
    {
36
        $this->httpClient = $httpClient;
37
        $this->apiKeyId = $apiKeyId;
38
        $this->apiKeySecret = $apiKeySecret;
39
        $this->boundary = substr(md5(microtime()), random_int(0, 26), 64);
40
    }
41
42 View Code Duplication
    public function createArticle(string $channelId, string $json, array $metadata = []): AppleNewsArticle
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
43
    {
44
        $path = "/channels/$channelId/articles";
45
        $response = $this->post($path, $json, $metadata);
46
47
        $jsonResponse = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
48
49
        return AppleNewsArticle::fromRawResponse($jsonResponse);
50
    }
51
52 View Code Duplication
    public function updateArticle(string $articleId, string $json, array $metadata = []): AppleNewsArticle
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
53
    {
54
        $path = "/articles/$articleId";
55
        $response = $this->post($path, $json, $metadata);
56
57
        $jsonResponse = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
58
59
        return AppleNewsArticle::fromRawResponse($jsonResponse);
60
    }
61
62
    public function deleteArticle(string $articleId): void
63
    {
64
        $path = "/articles/$articleId";
65
        $this->httpClient->delete($path, [
66
            'headers' => [
67
                'Authorization' => $this->getAuthorizationSignature('DELETE', $path),
68
            ],
69
        ]);
70
    }
71
72
    private function generateData(string $json, array $metadata): array
73
    {
74
        $data = [
75
            [
76
                'name' => 'article',
77
                'filename' => 'article.json',
78
                'contents' => $json,
79
                'headers' => [
80
                    'Content-Type' => 'application/json',
81
                ],
82
            ],
83
        ];
84
85
        if (!empty($metadata)) {
86
            $data[] = [
87
                'name' => 'metadata',
88
                'contents' => json_encode(['data' => $metadata], JSON_THROW_ON_ERROR, 512),
89
                'headers' => [
90
                    'Content-Type' => 'application/json',
91
                ],
92
            ];
93
        }
94
95
        return $data;
96
    }
97
98
    private function generateHhmacSignature(string $message): string
99
    {
100
        $keyBytes = base64_decode($this->apiKeySecret);
101
        $hashed = hash_hmac('sha256', $message, $keyBytes, true);
102
103
        return base64_encode($hashed);
104
    }
105
106
    private function getAuthorizationSignature(string $method, string $path, string $content = ''): string
107
    {
108
        $date = gmdate(\DateTime::ATOM);
109
        $url = ClientFactory::BASE_URI.$path;
110
        $canonical = $method.$url.$date.$content;
111
112
        $signature = $this->generateHhmacSignature($canonical, $this->apiKeySecret);
0 ignored issues
show
Unused Code introduced by
The call to AppleNewsApi::generateHhmacSignature() has too many arguments starting with $this->apiKeySecret.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
113
114
        return 'HHMAC; key="'.$this->apiKeyId.'"; signature="'.$signature.'"; date="'.$date.'"';
115
    }
116
117
    private function getContentType(): string
118
    {
119
        return 'multipart/form-data; boundary='.$this->boundary;
120
    }
121
122
    public function post(string $path, $json, array $metadata = []): ResponseInterface
123
    {
124
        $multipartStream = new MultipartStream($this->generateData($json, $metadata), $this->boundary);
125
126
        return $this->httpClient->post($path, [
127
            'body' => $multipartStream,
128
            'headers' => [
129
                'Authorization' => $this->getAuthorizationSignature('POST', $path, $this->getContentType().$multipartStream->getContents()),
130
                'Content-Type' => $this->getContentType(),
131
                'Content-Length' => strlen($json),
132
            ],
133
        ]);
134
    }
135
}
136