Completed
Push — master ( 897cdb...04ceba )
by Andrii
03:04
created

BaseController::findCommandNamespace()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
ccs 0
cts 9
cp 0
rs 9.4285
cc 1
eloc 7
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * HiAPI Yii2 base project for building API
4
 *
5
 * @link      https://github.com/hiqdev/hiapi
6
 * @package   hiapi
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiapi\controllers;
12
13
use Yii;
14
use yii\helpers\Inflector;
15
16
abstract class BaseController extends \yii\web\Controller
17
{
18
    protected $_actions;
19
20
    public function actions()
21
    {
22
        if ($this->_actions === null) {
23
            $this->_actions = $this->findActions();
24
        }
25
26
        return $this->_actions;
27
    }
28
29
    public function findActions()
30
    {
31
        $actions = [];
32
        foreach ($this->commands() as $name => $config) {
33
            $actions[$name] = [
34
                'class' => CommandAction::class,
35
                'command' => $config ?: $this->getCommandClass($name),
36
            ];
37
        }
38
39
        return $actions;
40
    }
41
42
    protected $_scannedCommands;
43
44
    public function commands()
45
    {
46
        if ($this->_scannedCommands === null) {
47
            $this->_scannedCommands = $this->scanCommands($this->getCommandNamespace());
48
        }
49
50
        return $this->_scannedCommands;
51
    }
52
53
    public function scanCommands($namespace)
54
    {
55
        $dir = Yii::getAlias('@' . strtr($namespace, '\\', '/'));
56
        if (!is_dir($dir)) {
57
            return [];
58
        }
59
60
        $commands = [];
61
        $files = scandir($dir);
62
        foreach ($files as $file) {
63
            if (substr_compare($file, 'Command.php', -11, 11) === 0) {
64
                $command = Inflector::camel2id(substr(basename($file), 0, -11));
65
                $commands[$command] = '';
66
            }
67
        }
68
69
        return $commands;
70
    }
71
72
    public function getCommandClass($name)
73
    {
74
        return $this->getCommandNamespace() . '\\' . Inflector::id2camel($name) . 'Command';
75
    }
76
77
    protected $_commandNamespace;
78
79
    public function getCommandNamespace()
80
    {
81
        if ($this->_commandNamespace === null) {
82
            $this->_commandNamespace = $this->findCommandNamespace();
83
        }
84
85
        return $this->_commandNamespace;
86
    }
87
88
    public function findCommandNamespace()
89
    {
90
        $nss = explode('\\', get_called_class());
91
        array_pop($nss);
92
        array_pop($nss);
93
        array_push($nss, 'commands');
94
        array_push($nss, $this->id);
95
96
        return implode('\\', $nss);
97
    }
98
}
99