Completed
Branch develop (9c1dc5)
by Timothy
07:15
created

KitsuTrait::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 12
nc 1
nop 0
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
/**
3
 * Anime List Client
4
 *
5
 * An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
6
 *
7
 * PHP version 7
8
 *
9
 * @package     AnimeListClient
10
 * @author      Timothy J. Warren <[email protected]>
11
 * @copyright   2015 - 2017  Timothy J. Warren
12
 * @license     http://www.opensource.org/licenses/mit-license.html  MIT License
13
 * @version     4.0
14
 * @link        https://github.com/timw4mail/HummingBirdAnimeClient
15
 */
16
17
namespace Aviat\AnimeClient\API\Kitsu;
18
19
use const Aviat\AnimeClient\SESSION_SEGMENT;
20
21
use function Amp\wait;
22
23
use Amp\Artax\Client;
24
use Aviat\AnimeClient\AnimeClient;
25
use Aviat\AnimeClient\API\Kitsu as K;
26
use Aviat\Ion\Json;
27
use InvalidArgumentException;
28
use RuntimeException;
29
30
trait KitsuTrait {
31
32
	/**
33
	 * The request builder for the MAL API
34
	 * @var MALRequestBuilder
35
	 */
36
	protected $requestBuilder;
37
38
	/**
39
	 * Set the request builder object
40
	 *
41
	 * @param KitsuRequestBuilder $requestBuilder
42
	 * @return self
43
	 */
44
	public function setRequestBuilder($requestBuilder): self
45
	{
46
		$this->requestBuilder = $requestBuilder;
0 ignored issues
show
Documentation Bug introduced by
It seems like $requestBuilder of type object<Aviat\AnimeClient...su\KitsuRequestBuilder> is incompatible with the declared type object<Aviat\AnimeClient...itsu\MALRequestBuilder> of property $requestBuilder.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
47
		return $this;
48
	}
49
50
	/**
51
	 * Create a request object
52
	 *
53
	 * @param string $type
54
	 * @param string $url
55
	 * @param array $options
56
	 * @return \Amp\Artax\Response
57
	 */
58
	public function setUpRequest(string $type, string $url, array $options = [])
59
	{
60
		$config = $this->container->get('config');
0 ignored issues
show
Bug introduced by
The property container does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Unused Code introduced by
$config is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
61
62
		$request = $this->requestBuilder->newRequest($type, $url);
63
64
		$sessionSegment = $this->getContainer()
0 ignored issues
show
Bug introduced by
It seems like getContainer() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
65
			->get('session')
66
			->getSegment(SESSION_SEGMENT);
67
68
		if ($sessionSegment->get('auth_token') !== null && $url !== K::AUTH_URL)
69
		{
70
			$token = $sessionSegment->get('auth_token');
71
			$request = $request->setAuth('bearer', $token);
72
			// $defaultOptions['headers']['Authorization'] = "bearer {$token}";
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
73
		}
74
		
75
		if (array_key_exists('form_params', $options))
76
		{
77
			$request->setFormFields($options['form_params']);
78
		}
79
80
		if (array_key_exists('query', $options))
81
		{
82
			$request->setQuery($options['query']);
83
		}
84
85
		if (array_key_exists('body', $options))
86
		{
87
			$request->setJsonBody($options['body']);
88
		}
89
90
		return $request->getFullRequest();
91
	}
92
93
	/**
94
	 * Make a request
95
	 *
96
	 * @param string $type
97
	 * @param string $url
98
	 * @param array $options
99
	 * @return Response
100
	 */
101
	private function getResponse(string $type, string $url, array $options = [])
102
	{
103
		$request = $this->setUpRequest($type, $url, $options);
104
		$logger = $this->container->getLogger('kitsu-request');
0 ignored issues
show
Unused Code introduced by
$logger is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
105
106
		$response = wait((new Client)->request($request));
107
108
		/* $logger->debug('Kitsu api response', [
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
109
			'status' => $response->getStatus(),
110
			'reason' => $response->getReason(),
111
			'body' => $response->getBody(),
112
			'headers' => $response->getAllHeaders(),
113
			'requestHeaders' => $request->getAllHeaders(),
114
		]); */
115
116
		return $response;
117
	}
118
119
	/**
120
	 * Make a request
121
	 *
122
	 * @param string $type
123
	 * @param string $url
124
	 * @param array $options
125
	 * @return array
126
	 */
127 View Code Duplication
	private function request(string $type, string $url, array $options = []): array
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...
128
	{
129
		$logger = null;
130
		if ($this->getContainer())
0 ignored issues
show
Bug introduced by
It seems like getContainer() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
131
		{
132
			$logger = $this->container->getLogger('kitsu-request');
133
		}
134
135
		$response = $this->getResponse($type, $url, $options);
136
137
		if ((int) $response->getStatus() > 299 || (int) $response->getStatus() < 200)
138
		{
139
			if ($logger)
140
			{
141
				$logger->warning('Non 200 response for api call', $response->getBody());
142
			}
143
		}
144
145
		return JSON::decode($response->getBody(), TRUE);
146
	}
147
148
	/**
149
	 * Remove some boilerplate for get requests
150
	 *
151
	 * @param array $args
152
	 * @return array
153
	 */
154
	protected function getRequest(...$args): array
155
	{
156
		return $this->request('GET', ...$args);
0 ignored issues
show
Documentation introduced by
$args is of type array<integer,array>, 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...
157
	}
158
159
	/**
160
	 * Remove some boilerplate for patch requests
161
	 *
162
	 * @param array $args
163
	 * @return array
164
	 */
165
	protected function patchRequest(...$args): array
166
	{
167
		return $this->request('PATCH', ...$args);
0 ignored issues
show
Documentation introduced by
$args is of type array<integer,array>, 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...
168
	}
169
170
	/**
171
	 * Remove some boilerplate for post requests
172
	 *
173
	 * @param array $args
174
	 * @return array
175
	 */
176 View Code Duplication
	protected function postRequest(...$args): array
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...
177
	{
178
		$logger = null;
179
		if ($this->getContainer())
0 ignored issues
show
Bug introduced by
It seems like getContainer() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
180
		{
181
			$logger = $this->container->getLogger('kitsu-request');
182
		}
183
184
		$response = $this->getResponse('POST', ...$args);
0 ignored issues
show
Documentation introduced by
$args is of type array<integer,array>, 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...
185
		$validResponseCodes = [200, 201];
186
187
		if ( ! in_array((int) $response->getStatus(), $validResponseCodes))
188
		{
189
			if ($logger)
190
			{
191
				$logger->warning('Non 201 response for POST api call', $response->getBody());
192
			}
193
		}
194
195
		return JSON::decode($response->getBody(), TRUE);
196
	}
197
198
	/**
199
	 * Remove some boilerplate for delete requests
200
	 *
201
	 * @param array $args
202
	 * @return bool
203
	 */
204
	protected function deleteRequest(...$args): bool
205
	{
206
		$response = $this->getResponse('DELETE', ...$args);
0 ignored issues
show
Documentation introduced by
$args is of type array<integer,array>, 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...
207
		return ((int) $response->getStatus() === 204);
208
	}
209
}