Passed
Pull Request — master (#190)
by Arman
02:52
created

ConsoleAppTrait   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 63
rs 10
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A validateCommand() 0 6 2
A registerCommands() 0 9 3
A registerCoreCommands() 0 6 1
A createApplication() 0 3 1
A registerAppCommands() 0 6 1
1
<?php
2
3
/**
4
 * Quantum PHP Framework
5
 *
6
 * An open source software development framework for PHP
7
 *
8
 * @package Quantum
9
 * @author Arman Ag. <[email protected]>
10
 * @copyright Copyright (c) 2018 Softberg LLC (https://softberg.org)
11
 * @link http://quantum.softberg.org/
12
 * @since 2.9.5
13
 */
14
15
namespace Quantum\App\Traits;
16
17
use Symfony\Component\Console\Input\ArgvInput;
18
use Symfony\Component\Console\Application;
19
use Quantum\Console\QtCommand;
20
use Mockery\Exception;
21
22
/**
23
 * Class ConsoleAppTrait
24
 * @package Quantum\App
25
 */
26
trait ConsoleAppTrait
27
{
28
29
    /**
30
     * @param string $name
31
     * @param string $version
32
     * @return Application
33
     */
34
    public function createApplication(string $name, string $version): Application
35
    {
36
        return new Application($name, $version);
37
    }
38
39
    /**
40
     * @return void
41
     */
42
    private function registerCoreCommands()
43
    {
44
        $directory = framework_dir() . DS . 'Console' . DS . 'Commands';
45
        $namespace = '\\Quantum\\Console\\Commands\\';
46
47
        $this->registerCommands($directory, $namespace);
48
    }
49
50
    /**
51
     * @return void
52
     */
53
    private function registerAppCommands()
54
    {
55
        $directory = base_dir() . DS . 'shared' . DS . 'Commands';
56
        $namespace = '\\Shared\\Commands\\';
57
58
        $this->registerCommands($directory, $namespace);
59
    }
60
61
    /**
62
     * @param string $directory
63
     * @param string $namespace
64
     * @return void
65
     */
66
    private function registerCommands(string $directory, string $namespace)
67
    {
68
        foreach (get_directory_classes($directory) as $className) {
69
            $commandClass = $namespace . $className;
70
71
            $command = new $commandClass();
72
73
            if ($command instanceof QtCommand) {
74
                $this->application->add($command);
75
            }
76
        }
77
    }
78
79
    /**
80
     * @param ArgvInput $input
81
     * @return void
82
     */
83
    private function validateCommand(ArgvInput $input): void
84
    {
85
        $commandName = $input->getFirstArgument();
86
87
        if (!$this->application->has($commandName)) {
88
            throw new Exception("Command `$commandName` is not defined");
89
        }
90
    }
91
}