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 ( e79432...6c8a4f )
by Freek
10:37 queued 08:25
created

Help::displayListOfAllCommands()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 10

Duplication

Lines 15
Ratio 100 %

Importance

Changes 0
Metric Value
dl 15
loc 15
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 10
nc 1
nop 1
1
<?php
2
3
namespace Spatie\SlashCommand\Handlers;
4
5
use Illuminate\Support\Collection;
6
use Illuminate\Support\Str;
7
use Spatie\SlashCommand\Attachment;
8
use Spatie\SlashCommand\AttachmentField;
9
use Spatie\SlashCommand\HandlesSlashCommand;
10
use Spatie\SlashCommand\Request;
11
use Spatie\SlashCommand\Response;
12
13
class Help extends SignatureHandler
14
{
15
    protected $signature = '* help {command? : The command you want information about}';
16
17
    protected $description = 'List all commands or provide information about all commands';
18
19
    /**
20
     * Handle the given request.
21
     *
22
     * @param \Spatie\SlashCommand\Request $request
23
     *
24
     * @return \Spatie\SlashCommand\Response
25
     */
26
    public function handle(Request $request): Response
27
    {
28
        $handlers = $this->findAvailableHandlers();
29
30
        if ($command = $this->getArgument('command')) {
31
            return $this->displayHelpForCommand($handlers, $command);
0 ignored issues
show
Bug introduced by
It seems like $handlers defined by $this->findAvailableHandlers() on line 28 can also be of type array<integer,object<Spa...lers\SignatureHandler>>; however, Spatie\SlashCommand\Hand...displayHelpForCommand() does only seem to accept object<Illuminate\Support\Collection>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
32
        }
33
34
        return $this->displayListOfAllCommands($handlers);
0 ignored issues
show
Bug introduced by
It seems like $handlers defined by $this->findAvailableHandlers() on line 28 can also be of type array<integer,object<Spa...lers\SignatureHandler>>; however, Spatie\SlashCommand\Hand...playListOfAllCommands() does only seem to accept object<Illuminate\Support\Collection>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
35
    }
36
37
    /**
38
     * Find all handlers that are available for the current SlashCommand
39
     * and have a signature.
40
     *
41
     * @return Collection|SignatureHandler[]
42
     */
43
    protected function findAvailableHandlers(): Collection
44
    {
45
        return collect(config('laravel-slack-slash-command.handlers'))
46
            ->map(function (string $handlerClassName) {
47
                return new $handlerClassName($this->request);
48
            })
49
            ->filter(function (HandlesSlashCommand $handler) {
50
                return $handler instanceof SignatureHandler;
51
            })
52 View Code Duplication
            ->filter(function (SignatureHandler $handler) {
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...
53
                $signatureParts = new SignatureParts($handler->getSignature());
54
55
                return Str::is($signatureParts->getSlashCommandName(), $this->request->command);
56
            });
57
    }
58
59
    /**
60
     * Show the help information for a single SignatureHandler.
61
     *
62
     * @param  Collection|SignatureHandler[] $handlers
63
     * @param  string $command
64
     * @return Response
65
     */
66
    protected function displayHelpForCommand(Collection $handlers, string $command): Response
67
    {
68
        $helpRequest = clone $this->request;
69
70
        $helpRequest->text = $command;
71
72
        /** @var \Spatie\SlashCommand\Handlers $handler */
73
        $handler = $handlers->filter(function (HandlesSlashCommand $handler) use ($helpRequest) {
74
            return $handler->canHandle($helpRequest);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Spatie\SlashCommand\HandlesSlashCommand as the method canHandle() does only exist in the following implementations of said interface: Spatie\SlashCommand\Handlers\BaseHandler, Spatie\SlashCommand\Handlers\CatchAll, Spatie\SlashCommand\Handlers\Help, Spatie\SlashCommand\Handlers\SignatureHandler.

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...
75
        })
76
            ->first();
77
78
        $field = AttachmentField::create($handler->getFullCommand(), $handler->getHelpDescription());
79
80
        return $this->respondToSlack('')
81
            ->withAttachment(
82
                Attachment::create()->addField($field)
83
            );
84
    }
85
86
    /**
87
     * Show a list of all available handlers.
88
     *
89
     * @param  Collection|SignatureHandler[] $handlers
90
     * @return Response
91
     */
92 View Code Duplication
    protected function displayListOfAllCommands(Collection $handlers): Response
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...
93
    {
94
        $attachmentFields = $handlers
95
            ->map(function (SignatureHandler $handler) {
96
                return AttachmentField::create($handler->getFullCommand(), $handler->getDescription());
97
            })
98
            ->all();
99
100
        return $this->respondToSlack('Available commands:')
101
            ->withAttachment(
102
                Attachment::create()
103
                    ->setColor('good')
104
                    ->setFields($attachmentFields)
105
            );
106
    }
107
}
108