GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 4e2a22...679227 )
by Cees-Jan
05:21
created

IteratePagesService   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 110
Duplicated Lines 10.91 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 45.83%

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 7
dl 12
loc 110
ccs 22
cts 48
cp 0.4583
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 2
B iterate() 6 37 6
A sendRequest() 0 14 1
C handleResponse() 6 34 8

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 declare(strict_types=1);
2
3
namespace ApiClients\Client\Github\Service;
4
5
use ApiClients\Foundation\Transport\Service\RequestService;
6
use Psr\Http\Message\ResponseInterface;
7
use React\Promise\CancellablePromiseInterface;
8
use RingCentral\Psr7\Request;
9
use Rx\AsyncSchedulerInterface;
10
use Rx\Disposable\CallbackDisposable;
11
use Rx\Observable;
12
use Rx\ObserverInterface;
13
use Rx\Scheduler;
14
use Rx\SchedulerInterface;
15
use Rx\Subject\Subject;
16
use function React\Promise\all;
17
use function React\Promise\resolve;
18
19
class IteratePagesService
20
{
21
    /**
22
     * @var RequestService
23
     */
24
    private $requestService;
25
26
    /**
27
     * @var AsyncSchedulerInterface
28
     */
29
    private $scheduler;
30
31
    /**
32
     * @param RequestService $requestService
33
     * @param AsyncSchedulerInterface $scheduler
34
     */
35 1
    public function __construct(RequestService $requestService, AsyncSchedulerInterface $scheduler = null)
36
    {
37 1
        $this->scheduler      = $scheduler ?: Scheduler::getAsync();
38 1
        $this->requestService = $requestService;
39 1
    }
40
41 1
    public function iterate(string $path): Observable
42
    {
43 1
        $paths = new Subject();
44
45 1
        return Observable::of($path, $this->scheduler)
46 1
            ->merge($paths)
47
            ->flatMap(function ($path) {
48 1
                return Observable::fromPromise($this->requestService->request(new Request('GET', $path)));
49 1
            })
50
            ->do(function (ResponseInterface $response) use ($paths) {
51 1
                if (!$response->hasHeader('link')) {
52
                    return;
53
                }
54
55
                $links = [
56 1
                    'next' => false,
57
                    'last' => false,
58
                ];
59 1 View Code Duplication
                foreach (explode(', ', $response->getHeader('link')[0]) as $link) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
60 1
                    list($url, $rel) = explode('>; rel="', ltrim(rtrim($link, '"'), '<'));
61 1
                    if (isset($links[$rel])) {
62 1
                        $links[$rel] = $url;
63
                    }
64
                }
65
66 1
                if ($links['next'] === false || $links['last'] === false) {
67
                    return;
68
                }
69
70
                $this->scheduler->schedule(function () use ($paths, $links) {
71 1
                    $paths->onNext($links['next']);
72 1
                });
73 1
            })
74
            ->map(function (ResponseInterface $response) {
75 1
                return $response->getBody()->getJson();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Http\Message\StreamInterface as the method getJson() does only exist in the following implementations of said interface: ApiClients\Middleware\Json\JsonStream.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
76 1
            });
77
    }
78
79
    private function sendRequest(string $path, Subject $subject)
80
    {
81
        $this->requestService->
82
            request(new Request('GET', $path))->
83
            then(
84
                function ($response) use ($subject) {
85
                    $this->handleResponse($response, $subject);
86
                },
87
                function ($error) use ($subject) {
88
                    $subject->onError($error);
89
                }
90
            )
91
        ;
92
    }
93
94
    private function handleResponse(
95
        ResponseInterface $response,
96
        Subject $subject
97
    ) {
98
        $subject->onNext($response->getBody()->getJson());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Http\Message\StreamInterface as the method getJson() does only exist in the following implementations of said interface: ApiClients\Middleware\Json\JsonStream.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
99
100
        if ($subject->isDisposed() || !$subject->hasObservers()) {
101
            $subject->onCompleted();
102
            return;
103
        }
104
105
        if (!$response->hasHeader('link')) {
106
            $subject->onCompleted();
107
            return;
108
        }
109
110
        $links = [
111
            'next' => false,
112
            'last' => false,
113
        ];
114 View Code Duplication
        foreach (explode(', ', $response->getHeader('link')[0]) as $link) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
115
            list($url, $rel) = explode('>; rel="', ltrim(rtrim($link, '"'), '<'));
116
            if (isset($links[$rel])) {
117
                $links[$rel] = $url;
118
            }
119
        }
120
121
        if ($links['next'] === false || $links['last'] === false) {
122
            $subject->onCompleted();
123
            return;
124
        }
125
126
        $this->sendRequest($links['next'], $subject);
127
    }
128
}
129