Passed
Push — master ( 3ed7ec...a3f41f )
by Korotkov
02:14 queued 11s
created

CreateMiddlewareCommand::createClass()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 6
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 11
rs 10
1
<?php
2
3
namespace App\Ship\Commands;
4
5
use Rudra\Cli\ConsoleFacade as Cli;
6
use Rudra\Container\Facades\Rudra;
7
8
class CreateMiddlewareCommand
9
{
10
    /**
11
     * Creates a file with Seed data
12
     * -----------------------------
13
     * Создает файл с данными Seed
14
     */
15
    public function actionIndex()
16
    {
17
        Cli::printer("Enter middleware name: ", "magneta");
18
        $prefix    = str_replace("\n", "", Cli::reader());
19
        $className = ucfirst($prefix) . 'Middleware';
20
21
        Cli::printer("Enter container: ", "magneta");
22
        $container = ucfirst(str_replace("\n", "", Cli::reader()));
23
24
        if (!empty($container)) {
25
26
            $this->writeFile(
27
                [Rudra::config()->get('app.path') . "/app/Containers/$container/Middleware/", "{$className}.php"],
28
                $this->createClass($className, $container)
29
            );
30
31
        } else {
32
            $this->actionIndex();
33
        }
34
    }
35
36
    /**
37
     * @param string $className
38
     * @param string $container
39
     * @return string
40
     *
41
     * Creates class data
42
     * ------------------
43
     * Создает данные класса
44
     */
45
    private function createClass(string $className, string $container)
46
    {
47
        return <<<EOT
48
<?php
49
50
namespace App\Containers\\{$container}\Middleware;
51
52
use Rudra\Router\MiddlewareInterface;
53
use Rudra\Router\RouterFacade as Router;
54
55
class {$className} implements MiddlewareInterface
56
{
57
    public function __invoke(\$middlewares)
58
    {
59
        \$this->info(__CLASS__);
60
        \$this->next(\$middlewares);
61
    }
62
63
    public function next(array \$middlewares): void
64
    {
65
        Router::handleMiddleware(\$middlewares);
66
    }
67
}
68
EOT;
69
    }
70
71
    /**
72
     * @param $path
73
     * @param $callable
74
     *
75
     * Writes data to a file
76
     * ---------------------
77
     * Записывает данные в файл
78
     */
79
    private function writeFile(array $path, string $data)
80
    {
81
        if (!is_dir($path[0])) {
82
            mkdir($path[0], 0755, true);
83
        }
84
85
        $fullPath = $path[0] . $path[1];
86
87
        if (!file_exists($fullPath)) {
88
            Cli::printer("The file ", "light_green");
89
            Cli::printer($fullPath, "light_green");
90
            Cli::printer(" was created\n", "light_green");
91
            file_put_contents($fullPath, $data);
92
        } else {
93
            Cli::printer("The file $fullPath is already exists\n", "light_yellow");
94
        }
95
    }
96
}
97