Completed
Push — master ( 961930...03cd17 )
by Ivan
10:43
created

BaseCommand::generateCommand()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 4
nop 1
1
<?php namespace FreedomCore\TrinityCore\Console\Abstracts;
2
3
/**
4
 * Class BaseCommand
5
 * @package FreedomCore\TrinityCore\Console\Abstracts
6
 */
7
abstract class BaseCommand {
8
9
    /**
10
     * Client Instance Object
11
     * @var null|\SoapClient
12
     */
13
    protected $clientInstance = null;
14
15
    /**
16
     * Name of the command
17
     * @var null|string
18
     */
19
    protected $command = null;
20
21
    /**
22
     * Available methods
23
     * @var array
24
     */
25
    protected $methods = [];
26
27
    /**
28
     * Commands which do not need to be prefixed with BASE command
29
     * @var array
30
     */
31
    protected $doNotPrefix = [];
32
33
    /**
34
     * Commands which methods should be concatenated
35
     * @var array
36
     */
37
    protected $concatenate = [];
38
39
    /**
40
     * BaseCommand constructor.
41
     * @param \SoapClient $client
42
     */
43
    public function __construct(\SoapClient $client) {
44
        $this->clientInstance = $client;
45
        $this->prepareCommand();
46
        $this->prepareMethods();
47
    }
48
49
    /**
50
     * Execute Help Command
51
     * @param string $methodName
52
     * @return string
53
     */
54
    public function help(string $methodName = '') {
55
        return $this->processOutput($this->clientInstance->executeCommand(new \SoapParam(trim(sprintf('help %s %s', $this->command, $methodName)), 'command')), true);
56
    }
57
58
    /**
59
     * Prepare Command Name Variable
60
     */
61
    protected function prepareCommand() {
62
        $this->command = strtolower((new \ReflectionClass(get_called_class()))->getShortName());
63
    }
64
65
    /**
66
     * Prepare Available Methods For Specified Command
67
     */
68
    protected function prepareMethods() {
69
        $globalMethods = get_class_methods(get_called_class());
70
        $classMethods = array_diff($globalMethods, ['__construct', 'prepareCommand', 'prepareMethods', 'generateCommand', 'generateQueryString', 'executeCommand', 'processOutput', 'help', 'inQuotes', 'parseCommand']);
71
        foreach ($classMethods as $method) {
72
            $command = $this->generateCommand($method);
73
            $this->methods[$method] = [
74
                'command'   =>  $command,
75
                'query'     =>  $this->generateQueryString(get_called_class(), $method)
76
            ];
77
        }
78
    }
79
80
    /**
81
     * Generate Command String
82
     * @param string $method
83
     * @return string
84
     */
85
    protected function generateCommand(string $method) : string {
86
        preg_match_all('/((?:^|[A-Z])[a-z]+)/', $method, $matches);
87
        $elements = array_map('strtolower', $matches[0]);
88
        $command = (!in_array($method, $this->doNotPrefix)) ? implode(' ', array_merge([$this->command], $elements)) : implode(' ', $elements);
89
        if (in_array($method, $this->concatenate))
90
            $command = $this->command . $method;
91
        return trim($this->parseCommand($command));
92
    }
93
94
    /**
95
     * Generate Command Query String
96
     * @param string $class
97
     * @param string $method
98
     * @return string
99
     */
100
    protected function generateQueryString(string $class, string $method) : string {
101
        $reflection =  new \ReflectionMethod($class, $method);
102
        return implode(' ', array_map(function( $item ) { return '%' . $item->getName() . '%'; }, $reflection->getParameters()));
103
    }
104
105
    /**
106
     * Add quotes to string
107
     * @param string $string
108
     * @return string
109
     */
110
    protected function inQuotes(string $string) : string {
111
        return '"' . $string . '"';
112
    }
113
114
    /**
115
     * Execute Command
116
     * @param string $methodName
117
     * @param array $parameters
118
     * @return array|string
119
     */
120
    protected function executeCommand(string $methodName, array $parameters) {
121
        $structure = [
122
            'class'         =>  get_called_class(),
123
            'method'        =>  $methodName,
124
            'parameters'    =>  $parameters,
125
            'query'         =>  $this->methods[$methodName]
126
        ];
127
        $structure['query']['prepared'] = str_replace('  ', ' ', trim(implode(' ', [
128
            $structure['query']['command'],
129
            str_replace(explode(' ', $structure['query']['query']), $structure['parameters'], $structure['query']['query'])
130
        ])));
131
        try {
132
            return $this->processOutput(
133
                $this->clientInstance->executeCommand(new \SoapParam(trim($structure['query']['prepared']), 'command'))
134
            );
135
        } catch (\SoapFault $exception) {
136
            return [
137
                'status'    =>  'failed',
138
                'code'      =>  $exception->getCode(),
139
                'message'   =>  trim($exception->getMessage()),
140
                'query'     =>  trim($structure['query']['prepared'])
141
            ];
142
        }
143
    }
144
145
    /**
146
     * Process Response
147
     * @param string $commandOutput
148
     * @param bool $helpFunction
149
     * @return array
150
     */
151
    protected function processOutput(string $commandOutput, bool $helpFunction = false) {
0 ignored issues
show
Unused Code introduced by
The parameter $helpFunction is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
152
        return array_filter(explode(PHP_EOL, $commandOutput));
153
    }
154
155
    /**
156
     * Parse and Process Command
157
     * @param string $command
158
     * @return string
159
     */
160
    protected function parseCommand(string $command) : string {
161
        $replacements = [
162
            'gm level'              =>  'gmlevel',
163
            'game account create'   =>  'gameaccountcreate',
164
            'list game accounts'    =>  'listgameaccounts',
165
            'diff time'             =>  'difftime',
166
            'log level'             =>  'loglevel',
167
            'save all'              =>  'saveall',
168
            'name announce'         =>  'nameannounce',
169
            'change faction'        =>  'changefaction',
170
            'change race'           =>  'changerace'
171
        ];
172
        foreach ($replacements as $key => $value) {
173
            if (strstr($command, $key)) {
174
                $command = str_replace($key, $value, $command);
175
                break;
176
            }
177
        }
178
        return $command;
179
    }
180
181
}