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 ( 8f129d...f20c64 )
by Cees-Jan
06:04
created

IteratePagesService::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 2
crap 2
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 RingCentral\Psr7\Request;
8
use Rx\AsyncSchedulerInterface;
9
use Rx\Observable;
10
use Rx\Scheduler;
11
use Rx\Subject\Subject;
12
13
class IteratePagesService
14
{
15
    /**
16
     * @var RequestService
17
     */
18
    private $requestService;
19
20
    /**
21
     * @var AsyncSchedulerInterface
22
     */
23
    private $scheduler;
24
25
    /**
26
     * @param RequestService          $requestService
27
     * @param AsyncSchedulerInterface $scheduler
28
     */
29 1
    public function __construct(RequestService $requestService, AsyncSchedulerInterface $scheduler = null)
30
    {
31 1
        $this->scheduler      = $scheduler ?: Scheduler::getAsync();
32 1
        $this->requestService = $requestService;
33 1
    }
34
35 1
    public function iterate(string $path): Observable
36
    {
37 1
        $paths = new Subject();
38
39 1
        return Observable::of($path, $this->scheduler)
40 1
            ->merge($paths)
41 1
            ->flatMap(function ($path) {
42 1
                return Observable::fromPromise($this->requestService->request(new Request('GET', $path)));
43 1
            })
44 1
            ->do(function (ResponseInterface $response) use ($paths) {
45 1
                if (!$response->hasHeader('link')) {
46
                    return;
47
                }
48
49
                $links = [
50 1
                    'next' => false,
51
                    'last' => false,
52
                ];
53 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...
54 1
                    list($url, $rel) = explode('>; rel="', ltrim(rtrim($link, '"'), '<'));
55 1
                    if (isset($links[$rel])) {
56 1
                        $links[$rel] = $url;
57
                    }
58
                }
59
60 1
                if ($links['next'] === false || $links['last'] === false) {
61
                    return;
62
                }
63
64 1
                $this->scheduler->schedule(function () use ($paths, $links) {
65 1
                    $paths->onNext($links['next']);
66 1
                });
67 1
            })
68 1
            ->map(function (ResponseInterface $response) {
69 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...
70 1
            });
71
    }
72
73
    private function sendRequest(string $path, Subject $subject)
74
    {
75
        $this->requestService->
76
            request(new Request('GET', $path))->
77
            then(
78
                function ($response) use ($subject) {
79
                    $this->handleResponse($response, $subject);
80
                },
81
                function ($error) use ($subject) {
82
                    $subject->onError($error);
83
                }
84
            )
85
        ;
86
    }
87
88
    private function handleResponse(
89
        ResponseInterface $response,
90
        Subject $subject
91
    ) {
92
        $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...
93
94
        if ($subject->isDisposed() || !$subject->hasObservers()) {
95
            $subject->onCompleted();
96
97
            return;
98
        }
99
100
        if (!$response->hasHeader('link')) {
101
            $subject->onCompleted();
102
103
            return;
104
        }
105
106
        $links = [
107
            'next' => false,
108
            'last' => false,
109
        ];
110 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...
111
            list($url, $rel) = explode('>; rel="', ltrim(rtrim($link, '"'), '<'));
112
            if (isset($links[$rel])) {
113
                $links[$rel] = $url;
114
            }
115
        }
116
117
        if ($links['next'] === false || $links['last'] === false) {
118
            $subject->onCompleted();
119
120
            return;
121
        }
122
123
        $this->sendRequest($links['next'], $subject);
124
    }
125
}
126