DefaultProvider   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
eloc 18
c 1
b 0
f 0
dl 0
loc 52
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B findCommands() 0 17 8
A register() 0 15 3
1
<?php
2
3
namespace PortlandLabs\Slackbot\Command;
4
5
use Illuminate\Support\Str;
6
use PortlandLabs\Slackbot\Bot;
7
8
class DefaultProvider implements Provider
9
{
10
11
    /** @var Command[]|string[] */
12
    protected $commands = [];
13
14
    /**
15
     * Handle adding commands to a bot
16
     *
17
     * @param Bot $bot
18
     * @return mixed
19
     */
20
    public function register(Bot $bot)
21
    {
22
        $manager = $bot->commands();
23
24
        // Add any subclass commands
25
        foreach ($this->commands as $command) {
26
            $manager->addCommand($command);
27
        }
28
29
        // Add all the default provided commands
30
        foreach ($this->findCommands() as $command) {
31
            $manager->addCommand($command);
32
        }
33
34
        return $manager;
35
    }
36
37
38
    /**
39
     * Find commands in the directory we expect to make the most of them
40
     *
41
     * @return iterable
42
     */
43
    public function findCommands(): iterable
44
    {
45
        foreach (scandir(__DIR__, SCANDIR_SORT_NONE) as $file) {
46
            if ($file === 'Command.php' || !Str::endsWith($file, 'Command.php')) {
47
                continue;
48
            }
49
50
            // Extract the classname
51
            $classname = __NAMESPACE__ . '\\' . Str::replaceLast('.php', '', $file);
52
            if (class_exists($classname) && !interface_exists($classname)) {
53
                try {
54
                    $class = new \ReflectionClass($classname);
55
56
                    if ($class->isInstantiable()) {
57
                        yield $classname;
58
                    }
59
                } catch (\ReflectionException $e) {
60
                    // Ignore classes we can't reflect
61
                }
62
            }
63
        }
64
    }
65
}